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/Sema/SemaInternal.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.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/Preprocessor.h"
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 "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallBitVector.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/Support/ConvertUTF.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <limits>
41 using namespace clang;
42 using namespace sema;
43 
44 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45                                                     unsigned ByteNo) const {
46   return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
47                                PP.getLangOpts(), PP.getTargetInfo());
48 }
49 
50 /// Checks that a call expression's argument count is the desired number.
51 /// This is useful when doing custom type-checking.  Returns true on error.
52 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53   unsigned argCount = call->getNumArgs();
54   if (argCount == desiredArgCount) return false;
55 
56   if (argCount < desiredArgCount)
57     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58         << 0 /*function call*/ << desiredArgCount << argCount
59         << call->getSourceRange();
60 
61   // Highlight all the excess arguments.
62   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63                     call->getArg(argCount - 1)->getLocEnd());
64 
65   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66     << 0 /*function call*/ << desiredArgCount << argCount
67     << call->getArg(1)->getSourceRange();
68 }
69 
70 /// Check that the first argument to __builtin_annotation is an integer
71 /// and the second argument is a non-wide string literal.
72 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73   if (checkArgCount(S, TheCall, 2))
74     return true;
75 
76   // First argument should be an integer.
77   Expr *ValArg = TheCall->getArg(0);
78   QualType Ty = ValArg->getType();
79   if (!Ty->isIntegerType()) {
80     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81       << ValArg->getSourceRange();
82     return true;
83   }
84 
85   // Second argument should be a constant string.
86   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88   if (!Literal || !Literal->isAscii()) {
89     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90       << StrArg->getSourceRange();
91     return true;
92   }
93 
94   TheCall->setType(Ty);
95   return false;
96 }
97 
98 /// Check that the argument to __builtin_addressof is a glvalue, and set the
99 /// result type to the corresponding pointer type.
100 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101   if (checkArgCount(S, TheCall, 1))
102     return true;
103 
104   ExprResult Arg(S.Owned(TheCall->getArg(0)));
105   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106   if (ResultType.isNull())
107     return true;
108 
109   TheCall->setArg(0, Arg.take());
110   TheCall->setType(ResultType);
111   return false;
112 }
113 
114 ExprResult
115 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
116   ExprResult TheCallResult(Owned(TheCall));
117 
118   // Find out if any arguments are required to be integer constant expressions.
119   unsigned ICEArguments = 0;
120   ASTContext::GetBuiltinTypeError Error;
121   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122   if (Error != ASTContext::GE_None)
123     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
124 
125   // If any arguments are required to be ICE's, check and diagnose.
126   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127     // Skip arguments not required to be ICE's.
128     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129 
130     llvm::APSInt Result;
131     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132       return true;
133     ICEArguments &= ~(1 << ArgNo);
134   }
135 
136   switch (BuiltinID) {
137   case Builtin::BI__builtin___CFStringMakeConstantString:
138     assert(TheCall->getNumArgs() == 1 &&
139            "Wrong # arguments to builtin CFStringMakeConstantString");
140     if (CheckObjCString(TheCall->getArg(0)))
141       return ExprError();
142     break;
143   case Builtin::BI__builtin_stdarg_start:
144   case Builtin::BI__builtin_va_start:
145     if (SemaBuiltinVAStart(TheCall))
146       return ExprError();
147     break;
148   case Builtin::BI__builtin_isgreater:
149   case Builtin::BI__builtin_isgreaterequal:
150   case Builtin::BI__builtin_isless:
151   case Builtin::BI__builtin_islessequal:
152   case Builtin::BI__builtin_islessgreater:
153   case Builtin::BI__builtin_isunordered:
154     if (SemaBuiltinUnorderedCompare(TheCall))
155       return ExprError();
156     break;
157   case Builtin::BI__builtin_fpclassify:
158     if (SemaBuiltinFPClassification(TheCall, 6))
159       return ExprError();
160     break;
161   case Builtin::BI__builtin_isfinite:
162   case Builtin::BI__builtin_isinf:
163   case Builtin::BI__builtin_isinf_sign:
164   case Builtin::BI__builtin_isnan:
165   case Builtin::BI__builtin_isnormal:
166     if (SemaBuiltinFPClassification(TheCall, 1))
167       return ExprError();
168     break;
169   case Builtin::BI__builtin_shufflevector:
170     return SemaBuiltinShuffleVector(TheCall);
171     // TheCall will be freed by the smart pointer here, but that's fine, since
172     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
173   case Builtin::BI__builtin_prefetch:
174     if (SemaBuiltinPrefetch(TheCall))
175       return ExprError();
176     break;
177   case Builtin::BI__builtin_object_size:
178     if (SemaBuiltinObjectSize(TheCall))
179       return ExprError();
180     break;
181   case Builtin::BI__builtin_longjmp:
182     if (SemaBuiltinLongjmp(TheCall))
183       return ExprError();
184     break;
185 
186   case Builtin::BI__builtin_classify_type:
187     if (checkArgCount(*this, TheCall, 1)) return true;
188     TheCall->setType(Context.IntTy);
189     break;
190   case Builtin::BI__builtin_constant_p:
191     if (checkArgCount(*this, TheCall, 1)) return true;
192     TheCall->setType(Context.IntTy);
193     break;
194   case Builtin::BI__sync_fetch_and_add:
195   case Builtin::BI__sync_fetch_and_add_1:
196   case Builtin::BI__sync_fetch_and_add_2:
197   case Builtin::BI__sync_fetch_and_add_4:
198   case Builtin::BI__sync_fetch_and_add_8:
199   case Builtin::BI__sync_fetch_and_add_16:
200   case Builtin::BI__sync_fetch_and_sub:
201   case Builtin::BI__sync_fetch_and_sub_1:
202   case Builtin::BI__sync_fetch_and_sub_2:
203   case Builtin::BI__sync_fetch_and_sub_4:
204   case Builtin::BI__sync_fetch_and_sub_8:
205   case Builtin::BI__sync_fetch_and_sub_16:
206   case Builtin::BI__sync_fetch_and_or:
207   case Builtin::BI__sync_fetch_and_or_1:
208   case Builtin::BI__sync_fetch_and_or_2:
209   case Builtin::BI__sync_fetch_and_or_4:
210   case Builtin::BI__sync_fetch_and_or_8:
211   case Builtin::BI__sync_fetch_and_or_16:
212   case Builtin::BI__sync_fetch_and_and:
213   case Builtin::BI__sync_fetch_and_and_1:
214   case Builtin::BI__sync_fetch_and_and_2:
215   case Builtin::BI__sync_fetch_and_and_4:
216   case Builtin::BI__sync_fetch_and_and_8:
217   case Builtin::BI__sync_fetch_and_and_16:
218   case Builtin::BI__sync_fetch_and_xor:
219   case Builtin::BI__sync_fetch_and_xor_1:
220   case Builtin::BI__sync_fetch_and_xor_2:
221   case Builtin::BI__sync_fetch_and_xor_4:
222   case Builtin::BI__sync_fetch_and_xor_8:
223   case Builtin::BI__sync_fetch_and_xor_16:
224   case Builtin::BI__sync_add_and_fetch:
225   case Builtin::BI__sync_add_and_fetch_1:
226   case Builtin::BI__sync_add_and_fetch_2:
227   case Builtin::BI__sync_add_and_fetch_4:
228   case Builtin::BI__sync_add_and_fetch_8:
229   case Builtin::BI__sync_add_and_fetch_16:
230   case Builtin::BI__sync_sub_and_fetch:
231   case Builtin::BI__sync_sub_and_fetch_1:
232   case Builtin::BI__sync_sub_and_fetch_2:
233   case Builtin::BI__sync_sub_and_fetch_4:
234   case Builtin::BI__sync_sub_and_fetch_8:
235   case Builtin::BI__sync_sub_and_fetch_16:
236   case Builtin::BI__sync_and_and_fetch:
237   case Builtin::BI__sync_and_and_fetch_1:
238   case Builtin::BI__sync_and_and_fetch_2:
239   case Builtin::BI__sync_and_and_fetch_4:
240   case Builtin::BI__sync_and_and_fetch_8:
241   case Builtin::BI__sync_and_and_fetch_16:
242   case Builtin::BI__sync_or_and_fetch:
243   case Builtin::BI__sync_or_and_fetch_1:
244   case Builtin::BI__sync_or_and_fetch_2:
245   case Builtin::BI__sync_or_and_fetch_4:
246   case Builtin::BI__sync_or_and_fetch_8:
247   case Builtin::BI__sync_or_and_fetch_16:
248   case Builtin::BI__sync_xor_and_fetch:
249   case Builtin::BI__sync_xor_and_fetch_1:
250   case Builtin::BI__sync_xor_and_fetch_2:
251   case Builtin::BI__sync_xor_and_fetch_4:
252   case Builtin::BI__sync_xor_and_fetch_8:
253   case Builtin::BI__sync_xor_and_fetch_16:
254   case Builtin::BI__sync_val_compare_and_swap:
255   case Builtin::BI__sync_val_compare_and_swap_1:
256   case Builtin::BI__sync_val_compare_and_swap_2:
257   case Builtin::BI__sync_val_compare_and_swap_4:
258   case Builtin::BI__sync_val_compare_and_swap_8:
259   case Builtin::BI__sync_val_compare_and_swap_16:
260   case Builtin::BI__sync_bool_compare_and_swap:
261   case Builtin::BI__sync_bool_compare_and_swap_1:
262   case Builtin::BI__sync_bool_compare_and_swap_2:
263   case Builtin::BI__sync_bool_compare_and_swap_4:
264   case Builtin::BI__sync_bool_compare_and_swap_8:
265   case Builtin::BI__sync_bool_compare_and_swap_16:
266   case Builtin::BI__sync_lock_test_and_set:
267   case Builtin::BI__sync_lock_test_and_set_1:
268   case Builtin::BI__sync_lock_test_and_set_2:
269   case Builtin::BI__sync_lock_test_and_set_4:
270   case Builtin::BI__sync_lock_test_and_set_8:
271   case Builtin::BI__sync_lock_test_and_set_16:
272   case Builtin::BI__sync_lock_release:
273   case Builtin::BI__sync_lock_release_1:
274   case Builtin::BI__sync_lock_release_2:
275   case Builtin::BI__sync_lock_release_4:
276   case Builtin::BI__sync_lock_release_8:
277   case Builtin::BI__sync_lock_release_16:
278   case Builtin::BI__sync_swap:
279   case Builtin::BI__sync_swap_1:
280   case Builtin::BI__sync_swap_2:
281   case Builtin::BI__sync_swap_4:
282   case Builtin::BI__sync_swap_8:
283   case Builtin::BI__sync_swap_16:
284     return SemaBuiltinAtomicOverloaded(TheCallResult);
285 #define BUILTIN(ID, TYPE, ATTRS)
286 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287   case Builtin::BI##ID: \
288     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
289 #include "clang/Basic/Builtins.def"
290   case Builtin::BI__builtin_annotation:
291     if (SemaBuiltinAnnotation(*this, TheCall))
292       return ExprError();
293     break;
294   case Builtin::BI__builtin_addressof:
295     if (SemaBuiltinAddressof(*this, TheCall))
296       return ExprError();
297     break;
298   }
299 
300   // Since the target specific builtins for each arch overlap, only check those
301   // of the arch we are compiling for.
302   if (BuiltinID >= Builtin::FirstTSBuiltin) {
303     switch (Context.getTargetInfo().getTriple().getArch()) {
304       case llvm::Triple::arm:
305       case llvm::Triple::thumb:
306         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
307           return ExprError();
308         break;
309       case llvm::Triple::aarch64:
310       case llvm::Triple::aarch64_be:
311         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
312           return ExprError();
313         break;
314       case llvm::Triple::mips:
315       case llvm::Triple::mipsel:
316       case llvm::Triple::mips64:
317       case llvm::Triple::mips64el:
318         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
319           return ExprError();
320         break;
321       case llvm::Triple::x86:
322       case llvm::Triple::x86_64:
323         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
324           return ExprError();
325         break;
326       default:
327         break;
328     }
329   }
330 
331   return TheCallResult;
332 }
333 
334 // Get the valid immediate range for the specified NEON type code.
335 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
336   NeonTypeFlags Type(t);
337   int IsQuad = ForceQuad ? true : Type.isQuad();
338   switch (Type.getEltType()) {
339   case NeonTypeFlags::Int8:
340   case NeonTypeFlags::Poly8:
341     return shift ? 7 : (8 << IsQuad) - 1;
342   case NeonTypeFlags::Int16:
343   case NeonTypeFlags::Poly16:
344     return shift ? 15 : (4 << IsQuad) - 1;
345   case NeonTypeFlags::Int32:
346     return shift ? 31 : (2 << IsQuad) - 1;
347   case NeonTypeFlags::Int64:
348   case NeonTypeFlags::Poly64:
349     return shift ? 63 : (1 << IsQuad) - 1;
350   case NeonTypeFlags::Poly128:
351     return shift ? 127 : (1 << IsQuad) - 1;
352   case NeonTypeFlags::Float16:
353     assert(!shift && "cannot shift float types!");
354     return (4 << IsQuad) - 1;
355   case NeonTypeFlags::Float32:
356     assert(!shift && "cannot shift float types!");
357     return (2 << IsQuad) - 1;
358   case NeonTypeFlags::Float64:
359     assert(!shift && "cannot shift float types!");
360     return (1 << IsQuad) - 1;
361   }
362   llvm_unreachable("Invalid NeonTypeFlag!");
363 }
364 
365 /// getNeonEltType - Return the QualType corresponding to the elements of
366 /// the vector type specified by the NeonTypeFlags.  This is used to check
367 /// the pointer arguments for Neon load/store intrinsics.
368 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
369                                bool IsAArch64) {
370   switch (Flags.getEltType()) {
371   case NeonTypeFlags::Int8:
372     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
373   case NeonTypeFlags::Int16:
374     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
375   case NeonTypeFlags::Int32:
376     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
377   case NeonTypeFlags::Int64:
378     if (IsAArch64)
379       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
380     else
381       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
382                                 : Context.LongLongTy;
383   case NeonTypeFlags::Poly8:
384     return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
385   case NeonTypeFlags::Poly16:
386     return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
387   case NeonTypeFlags::Poly64:
388     return Context.UnsignedLongTy;
389   case NeonTypeFlags::Poly128:
390     break;
391   case NeonTypeFlags::Float16:
392     return Context.HalfTy;
393   case NeonTypeFlags::Float32:
394     return Context.FloatTy;
395   case NeonTypeFlags::Float64:
396     return Context.DoubleTy;
397   }
398   llvm_unreachable("Invalid NeonTypeFlag!");
399 }
400 
401 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
402   llvm::APSInt Result;
403   uint64_t mask = 0;
404   unsigned TV = 0;
405   int PtrArgNum = -1;
406   bool HasConstPtr = false;
407   switch (BuiltinID) {
408 #define GET_NEON_OVERLOAD_CHECK
409 #include "clang/Basic/arm_neon.inc"
410 #undef GET_NEON_OVERLOAD_CHECK
411   }
412 
413   // For NEON intrinsics which are overloaded on vector element type, validate
414   // the immediate which specifies which variant to emit.
415   unsigned ImmArg = TheCall->getNumArgs()-1;
416   if (mask) {
417     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
418       return true;
419 
420     TV = Result.getLimitedValue(64);
421     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
422       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
423         << TheCall->getArg(ImmArg)->getSourceRange();
424   }
425 
426   if (PtrArgNum >= 0) {
427     // Check that pointer arguments have the specified type.
428     Expr *Arg = TheCall->getArg(PtrArgNum);
429     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
430       Arg = ICE->getSubExpr();
431     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
432     QualType RHSTy = RHS.get()->getType();
433 
434     bool IsAArch64 =
435         Context.getTargetInfo().getTriple().getArch() == llvm::Triple::aarch64;
436     QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, IsAArch64);
437     if (HasConstPtr)
438       EltTy = EltTy.withConst();
439     QualType LHSTy = Context.getPointerType(EltTy);
440     AssignConvertType ConvTy;
441     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
442     if (RHS.isInvalid())
443       return true;
444     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
445                                  RHS.get(), AA_Assigning))
446       return true;
447   }
448 
449   // For NEON intrinsics which take an immediate value as part of the
450   // instruction, range check them here.
451   unsigned i = 0, l = 0, u = 0;
452   switch (BuiltinID) {
453   default:
454     return false;
455 #define GET_NEON_IMMEDIATE_CHECK
456 #include "clang/Basic/arm_neon.inc"
457 #undef GET_NEON_IMMEDIATE_CHECK
458   }
459   ;
460 
461   // We can't check the value of a dependent argument.
462   if (TheCall->getArg(i)->isTypeDependent() ||
463       TheCall->getArg(i)->isValueDependent())
464     return false;
465 
466   // Check that the immediate argument is actually a constant.
467   if (SemaBuiltinConstantArg(TheCall, i, Result))
468     return true;
469 
470   // Range check against the upper/lower values for this isntruction.
471   unsigned Val = Result.getZExtValue();
472   if (Val < l || Val > (u + l))
473     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
474            << l << u + l << TheCall->getArg(i)->getSourceRange();
475 
476   return false;
477 }
478 
479 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
480                                            CallExpr *TheCall) {
481   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
482     return true;
483 
484   return false;
485 }
486 
487 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
488   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
489           BuiltinID == ARM::BI__builtin_arm_strex) &&
490          "unexpected ARM builtin");
491   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
492 
493   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
494 
495   // Ensure that we have the proper number of arguments.
496   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
497     return true;
498 
499   // Inspect the pointer argument of the atomic builtin.  This should always be
500   // a pointer type, whose element is an integral scalar or pointer type.
501   // Because it is a pointer type, we don't have to worry about any implicit
502   // casts here.
503   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
504   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
505   if (PointerArgRes.isInvalid())
506     return true;
507   PointerArg = PointerArgRes.take();
508 
509   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
510   if (!pointerType) {
511     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
512       << PointerArg->getType() << PointerArg->getSourceRange();
513     return true;
514   }
515 
516   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
517   // task is to insert the appropriate casts into the AST. First work out just
518   // what the appropriate type is.
519   QualType ValType = pointerType->getPointeeType();
520   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
521   if (IsLdrex)
522     AddrType.addConst();
523 
524   // Issue a warning if the cast is dodgy.
525   CastKind CastNeeded = CK_NoOp;
526   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
527     CastNeeded = CK_BitCast;
528     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
529       << PointerArg->getType()
530       << Context.getPointerType(AddrType)
531       << AA_Passing << PointerArg->getSourceRange();
532   }
533 
534   // Finally, do the cast and replace the argument with the corrected version.
535   AddrType = Context.getPointerType(AddrType);
536   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
537   if (PointerArgRes.isInvalid())
538     return true;
539   PointerArg = PointerArgRes.take();
540 
541   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
542 
543   // In general, we allow ints, floats and pointers to be loaded and stored.
544   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
545       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
546     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
547       << PointerArg->getType() << PointerArg->getSourceRange();
548     return true;
549   }
550 
551   // But ARM doesn't have instructions to deal with 128-bit versions.
552   if (Context.getTypeSize(ValType) > 64) {
553     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
554       << PointerArg->getType() << PointerArg->getSourceRange();
555     return true;
556   }
557 
558   switch (ValType.getObjCLifetime()) {
559   case Qualifiers::OCL_None:
560   case Qualifiers::OCL_ExplicitNone:
561     // okay
562     break;
563 
564   case Qualifiers::OCL_Weak:
565   case Qualifiers::OCL_Strong:
566   case Qualifiers::OCL_Autoreleasing:
567     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
568       << ValType << PointerArg->getSourceRange();
569     return true;
570   }
571 
572 
573   if (IsLdrex) {
574     TheCall->setType(ValType);
575     return false;
576   }
577 
578   // Initialize the argument to be stored.
579   ExprResult ValArg = TheCall->getArg(0);
580   InitializedEntity Entity = InitializedEntity::InitializeParameter(
581       Context, ValType, /*consume*/ false);
582   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
583   if (ValArg.isInvalid())
584     return true;
585   TheCall->setArg(0, ValArg.get());
586 
587   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
588   // but the custom checker bypasses all default analysis.
589   TheCall->setType(Context.IntTy);
590   return false;
591 }
592 
593 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
594   llvm::APSInt Result;
595 
596   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
597       BuiltinID == ARM::BI__builtin_arm_strex) {
598     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
599   }
600 
601   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
602     return true;
603 
604   // For NEON intrinsics which take an immediate value as part of the
605   // instruction, range check them here.
606   unsigned i = 0, l = 0, u = 0;
607   switch (BuiltinID) {
608   default: return false;
609   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
610   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
611   case ARM::BI__builtin_arm_vcvtr_f:
612   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
613   case ARM::BI__builtin_arm_dmb:
614   case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
615   };
616 
617   // We can't check the value of a dependent argument.
618   if (TheCall->getArg(i)->isTypeDependent() ||
619       TheCall->getArg(i)->isValueDependent())
620     return false;
621 
622   // Check that the immediate argument is actually a constant.
623   if (SemaBuiltinConstantArg(TheCall, i, Result))
624     return true;
625 
626   // Range check against the upper/lower values for this isntruction.
627   unsigned Val = Result.getZExtValue();
628   if (Val < l || Val > (u + l))
629     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
630       << l << u+l << TheCall->getArg(i)->getSourceRange();
631 
632   // FIXME: VFP Intrinsics should error if VFP not present.
633   return false;
634 }
635 
636 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
637   unsigned i = 0, l = 0, u = 0;
638   switch (BuiltinID) {
639   default: return false;
640   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
641   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
642   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
643   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
644   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
645   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
646   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
647   };
648 
649   // We can't check the value of a dependent argument.
650   if (TheCall->getArg(i)->isTypeDependent() ||
651       TheCall->getArg(i)->isValueDependent())
652     return false;
653 
654   // Check that the immediate argument is actually a constant.
655   llvm::APSInt Result;
656   if (SemaBuiltinConstantArg(TheCall, i, Result))
657     return true;
658 
659   // Range check against the upper/lower values for this instruction.
660   unsigned Val = Result.getZExtValue();
661   if (Val < l || Val > u)
662     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
663       << l << u << TheCall->getArg(i)->getSourceRange();
664 
665   return false;
666 }
667 
668 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
669   switch (BuiltinID) {
670   case X86::BI_mm_prefetch:
671     return SemaBuiltinMMPrefetch(TheCall);
672     break;
673   }
674   return false;
675 }
676 
677 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
678 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
679 /// Returns true when the format fits the function and the FormatStringInfo has
680 /// been populated.
681 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
682                                FormatStringInfo *FSI) {
683   FSI->HasVAListArg = Format->getFirstArg() == 0;
684   FSI->FormatIdx = Format->getFormatIdx() - 1;
685   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
686 
687   // The way the format attribute works in GCC, the implicit this argument
688   // of member functions is counted. However, it doesn't appear in our own
689   // lists, so decrement format_idx in that case.
690   if (IsCXXMember) {
691     if(FSI->FormatIdx == 0)
692       return false;
693     --FSI->FormatIdx;
694     if (FSI->FirstDataArg != 0)
695       --FSI->FirstDataArg;
696   }
697   return true;
698 }
699 
700 /// Checks if a the given expression evaluates to null.
701 ///
702 /// \brief Returns true if the value evaluates to null.
703 static bool CheckNonNullExpr(Sema &S,
704                              const Expr *Expr) {
705   // As a special case, transparent unions initialized with zero are
706   // considered null for the purposes of the nonnull attribute.
707   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
708     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
709       if (const CompoundLiteralExpr *CLE =
710           dyn_cast<CompoundLiteralExpr>(Expr))
711         if (const InitListExpr *ILE =
712             dyn_cast<InitListExpr>(CLE->getInitializer()))
713           Expr = ILE->getInit(0);
714   }
715 
716   bool Result;
717   return (!Expr->isValueDependent() &&
718           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
719           !Result);
720 }
721 
722 static void CheckNonNullArgument(Sema &S,
723                                  const Expr *ArgExpr,
724                                  SourceLocation CallSiteLoc) {
725   if (CheckNonNullExpr(S, ArgExpr))
726     S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
727 }
728 
729 static void CheckNonNullArguments(Sema &S,
730                                   const NamedDecl *FDecl,
731                                   const Expr * const *ExprArgs,
732                                   SourceLocation CallSiteLoc) {
733   // Check the attributes attached to the method/function itself.
734   for (specific_attr_iterator<NonNullAttr>
735        I = FDecl->specific_attr_begin<NonNullAttr>(),
736        E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) {
737 
738     const NonNullAttr *NonNull = *I;
739     for (NonNullAttr::args_iterator i = NonNull->args_begin(),
740          e = NonNull->args_end();
741          i != e; ++i) {
742       CheckNonNullArgument(S, ExprArgs[*i], CallSiteLoc);
743     }
744   }
745 
746   // Check the attributes on the parameters.
747   ArrayRef<ParmVarDecl*> parms;
748   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
749     parms = FD->parameters();
750   else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
751     parms = MD->parameters();
752 
753   unsigned argIndex = 0;
754   for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
755        I != E; ++I, ++argIndex) {
756     const ParmVarDecl *PVD = *I;
757     if (PVD->hasAttr<NonNullAttr>())
758       CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
759   }
760 }
761 
762 /// Handles the checks for format strings, non-POD arguments to vararg
763 /// functions, and NULL arguments passed to non-NULL parameters.
764 void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
765                      unsigned NumParams, bool IsMemberFunction,
766                      SourceLocation Loc, SourceRange Range,
767                      VariadicCallType CallType) {
768   // FIXME: We should check as much as we can in the template definition.
769   if (CurContext->isDependentContext())
770     return;
771 
772   // Printf and scanf checking.
773   llvm::SmallBitVector CheckedVarArgs;
774   if (FDecl) {
775     for (specific_attr_iterator<FormatAttr>
776              I = FDecl->specific_attr_begin<FormatAttr>(),
777              E = FDecl->specific_attr_end<FormatAttr>();
778          I != E; ++I) {
779       // Only create vector if there are format attributes.
780       CheckedVarArgs.resize(Args.size());
781 
782       CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
783                            CheckedVarArgs);
784     }
785   }
786 
787   // Refuse POD arguments that weren't caught by the format string
788   // checks above.
789   if (CallType != VariadicDoesNotApply) {
790     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
791       // Args[ArgIdx] can be null in malformed code.
792       if (const Expr *Arg = Args[ArgIdx]) {
793         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
794           checkVariadicArgument(Arg, CallType);
795       }
796     }
797   }
798 
799   if (FDecl) {
800     CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
801 
802     // Type safety checking.
803     for (specific_attr_iterator<ArgumentWithTypeTagAttr>
804            i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
805            e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
806          i != e; ++i) {
807       CheckArgumentWithTypeTag(*i, Args.data());
808     }
809   }
810 }
811 
812 /// CheckConstructorCall - Check a constructor call for correctness and safety
813 /// properties not enforced by the C type system.
814 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
815                                 ArrayRef<const Expr *> Args,
816                                 const FunctionProtoType *Proto,
817                                 SourceLocation Loc) {
818   VariadicCallType CallType =
819     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
820   checkCall(FDecl, Args, Proto->getNumParams(),
821             /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
822 }
823 
824 /// CheckFunctionCall - Check a direct function call for various correctness
825 /// and safety properties not strictly enforced by the C type system.
826 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
827                              const FunctionProtoType *Proto) {
828   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
829                               isa<CXXMethodDecl>(FDecl);
830   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
831                           IsMemberOperatorCall;
832   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
833                                                   TheCall->getCallee());
834   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
835   Expr** Args = TheCall->getArgs();
836   unsigned NumArgs = TheCall->getNumArgs();
837   if (IsMemberOperatorCall) {
838     // If this is a call to a member operator, hide the first argument
839     // from checkCall.
840     // FIXME: Our choice of AST representation here is less than ideal.
841     ++Args;
842     --NumArgs;
843   }
844   checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
845             IsMemberFunction, TheCall->getRParenLoc(),
846             TheCall->getCallee()->getSourceRange(), CallType);
847 
848   IdentifierInfo *FnInfo = FDecl->getIdentifier();
849   // None of the checks below are needed for functions that don't have
850   // simple names (e.g., C++ conversion functions).
851   if (!FnInfo)
852     return false;
853 
854   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
855 
856   unsigned CMId = FDecl->getMemoryFunctionKind();
857   if (CMId == 0)
858     return false;
859 
860   // Handle memory setting and copying functions.
861   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
862     CheckStrlcpycatArguments(TheCall, FnInfo);
863   else if (CMId == Builtin::BIstrncat)
864     CheckStrncatArguments(TheCall, FnInfo);
865   else
866     CheckMemaccessArguments(TheCall, CMId, FnInfo);
867 
868   return false;
869 }
870 
871 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
872                                ArrayRef<const Expr *> Args) {
873   VariadicCallType CallType =
874       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
875 
876   checkCall(Method, Args, Method->param_size(),
877             /*IsMemberFunction=*/false,
878             lbrac, Method->getSourceRange(), CallType);
879 
880   return false;
881 }
882 
883 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
884                             const FunctionProtoType *Proto) {
885   const VarDecl *V = dyn_cast<VarDecl>(NDecl);
886   if (!V)
887     return false;
888 
889   QualType Ty = V->getType();
890   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
891     return false;
892 
893   VariadicCallType CallType;
894   if (!Proto || !Proto->isVariadic()) {
895     CallType = VariadicDoesNotApply;
896   } else if (Ty->isBlockPointerType()) {
897     CallType = VariadicBlock;
898   } else { // Ty->isFunctionPointerType()
899     CallType = VariadicFunction;
900   }
901   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
902 
903   checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
904                                                     TheCall->getNumArgs()),
905             NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
906             TheCall->getCallee()->getSourceRange(), CallType);
907 
908   return false;
909 }
910 
911 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
912 /// such as function pointers returned from functions.
913 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
914   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
915                                                   TheCall->getCallee());
916   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
917 
918   checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>(
919                              TheCall->getArgs(), TheCall->getNumArgs()),
920             NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
921             TheCall->getCallee()->getSourceRange(), CallType);
922 
923   return false;
924 }
925 
926 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
927                                          AtomicExpr::AtomicOp Op) {
928   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
929   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
930 
931   // All these operations take one of the following forms:
932   enum {
933     // C    __c11_atomic_init(A *, C)
934     Init,
935     // C    __c11_atomic_load(A *, int)
936     Load,
937     // void __atomic_load(A *, CP, int)
938     Copy,
939     // C    __c11_atomic_add(A *, M, int)
940     Arithmetic,
941     // C    __atomic_exchange_n(A *, CP, int)
942     Xchg,
943     // void __atomic_exchange(A *, C *, CP, int)
944     GNUXchg,
945     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
946     C11CmpXchg,
947     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
948     GNUCmpXchg
949   } Form = Init;
950   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
951   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
952   // where:
953   //   C is an appropriate type,
954   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
955   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
956   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
957   //   the int parameters are for orderings.
958 
959   assert(AtomicExpr::AO__c11_atomic_init == 0 &&
960          AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
961          && "need to update code for modified C11 atomics");
962   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
963                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
964   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
965              Op == AtomicExpr::AO__atomic_store_n ||
966              Op == AtomicExpr::AO__atomic_exchange_n ||
967              Op == AtomicExpr::AO__atomic_compare_exchange_n;
968   bool IsAddSub = false;
969 
970   switch (Op) {
971   case AtomicExpr::AO__c11_atomic_init:
972     Form = Init;
973     break;
974 
975   case AtomicExpr::AO__c11_atomic_load:
976   case AtomicExpr::AO__atomic_load_n:
977     Form = Load;
978     break;
979 
980   case AtomicExpr::AO__c11_atomic_store:
981   case AtomicExpr::AO__atomic_load:
982   case AtomicExpr::AO__atomic_store:
983   case AtomicExpr::AO__atomic_store_n:
984     Form = Copy;
985     break;
986 
987   case AtomicExpr::AO__c11_atomic_fetch_add:
988   case AtomicExpr::AO__c11_atomic_fetch_sub:
989   case AtomicExpr::AO__atomic_fetch_add:
990   case AtomicExpr::AO__atomic_fetch_sub:
991   case AtomicExpr::AO__atomic_add_fetch:
992   case AtomicExpr::AO__atomic_sub_fetch:
993     IsAddSub = true;
994     // Fall through.
995   case AtomicExpr::AO__c11_atomic_fetch_and:
996   case AtomicExpr::AO__c11_atomic_fetch_or:
997   case AtomicExpr::AO__c11_atomic_fetch_xor:
998   case AtomicExpr::AO__atomic_fetch_and:
999   case AtomicExpr::AO__atomic_fetch_or:
1000   case AtomicExpr::AO__atomic_fetch_xor:
1001   case AtomicExpr::AO__atomic_fetch_nand:
1002   case AtomicExpr::AO__atomic_and_fetch:
1003   case AtomicExpr::AO__atomic_or_fetch:
1004   case AtomicExpr::AO__atomic_xor_fetch:
1005   case AtomicExpr::AO__atomic_nand_fetch:
1006     Form = Arithmetic;
1007     break;
1008 
1009   case AtomicExpr::AO__c11_atomic_exchange:
1010   case AtomicExpr::AO__atomic_exchange_n:
1011     Form = Xchg;
1012     break;
1013 
1014   case AtomicExpr::AO__atomic_exchange:
1015     Form = GNUXchg;
1016     break;
1017 
1018   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1019   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1020     Form = C11CmpXchg;
1021     break;
1022 
1023   case AtomicExpr::AO__atomic_compare_exchange:
1024   case AtomicExpr::AO__atomic_compare_exchange_n:
1025     Form = GNUCmpXchg;
1026     break;
1027   }
1028 
1029   // Check we have the right number of arguments.
1030   if (TheCall->getNumArgs() < NumArgs[Form]) {
1031     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1032       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1033       << TheCall->getCallee()->getSourceRange();
1034     return ExprError();
1035   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1036     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
1037          diag::err_typecheck_call_too_many_args)
1038       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1039       << TheCall->getCallee()->getSourceRange();
1040     return ExprError();
1041   }
1042 
1043   // Inspect the first argument of the atomic operation.
1044   Expr *Ptr = TheCall->getArg(0);
1045   Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1046   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1047   if (!pointerType) {
1048     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1049       << Ptr->getType() << Ptr->getSourceRange();
1050     return ExprError();
1051   }
1052 
1053   // For a __c11 builtin, this should be a pointer to an _Atomic type.
1054   QualType AtomTy = pointerType->getPointeeType(); // 'A'
1055   QualType ValType = AtomTy; // 'C'
1056   if (IsC11) {
1057     if (!AtomTy->isAtomicType()) {
1058       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1059         << Ptr->getType() << Ptr->getSourceRange();
1060       return ExprError();
1061     }
1062     if (AtomTy.isConstQualified()) {
1063       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1064         << Ptr->getType() << Ptr->getSourceRange();
1065       return ExprError();
1066     }
1067     ValType = AtomTy->getAs<AtomicType>()->getValueType();
1068   }
1069 
1070   // For an arithmetic operation, the implied arithmetic must be well-formed.
1071   if (Form == Arithmetic) {
1072     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1073     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1074       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1075         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1076       return ExprError();
1077     }
1078     if (!IsAddSub && !ValType->isIntegerType()) {
1079       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1080         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1081       return ExprError();
1082     }
1083   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1084     // For __atomic_*_n operations, the value type must be a scalar integral or
1085     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1086     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1087       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1088     return ExprError();
1089   }
1090 
1091   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1092       !AtomTy->isScalarType()) {
1093     // For GNU atomics, require a trivially-copyable type. This is not part of
1094     // the GNU atomics specification, but we enforce it for sanity.
1095     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1096       << Ptr->getType() << Ptr->getSourceRange();
1097     return ExprError();
1098   }
1099 
1100   // FIXME: For any builtin other than a load, the ValType must not be
1101   // const-qualified.
1102 
1103   switch (ValType.getObjCLifetime()) {
1104   case Qualifiers::OCL_None:
1105   case Qualifiers::OCL_ExplicitNone:
1106     // okay
1107     break;
1108 
1109   case Qualifiers::OCL_Weak:
1110   case Qualifiers::OCL_Strong:
1111   case Qualifiers::OCL_Autoreleasing:
1112     // FIXME: Can this happen? By this point, ValType should be known
1113     // to be trivially copyable.
1114     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1115       << ValType << Ptr->getSourceRange();
1116     return ExprError();
1117   }
1118 
1119   QualType ResultType = ValType;
1120   if (Form == Copy || Form == GNUXchg || Form == Init)
1121     ResultType = Context.VoidTy;
1122   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1123     ResultType = Context.BoolTy;
1124 
1125   // The type of a parameter passed 'by value'. In the GNU atomics, such
1126   // arguments are actually passed as pointers.
1127   QualType ByValType = ValType; // 'CP'
1128   if (!IsC11 && !IsN)
1129     ByValType = Ptr->getType();
1130 
1131   // The first argument --- the pointer --- has a fixed type; we
1132   // deduce the types of the rest of the arguments accordingly.  Walk
1133   // the remaining arguments, converting them to the deduced value type.
1134   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1135     QualType Ty;
1136     if (i < NumVals[Form] + 1) {
1137       switch (i) {
1138       case 1:
1139         // The second argument is the non-atomic operand. For arithmetic, this
1140         // is always passed by value, and for a compare_exchange it is always
1141         // passed by address. For the rest, GNU uses by-address and C11 uses
1142         // by-value.
1143         assert(Form != Load);
1144         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1145           Ty = ValType;
1146         else if (Form == Copy || Form == Xchg)
1147           Ty = ByValType;
1148         else if (Form == Arithmetic)
1149           Ty = Context.getPointerDiffType();
1150         else
1151           Ty = Context.getPointerType(ValType.getUnqualifiedType());
1152         break;
1153       case 2:
1154         // The third argument to compare_exchange / GNU exchange is a
1155         // (pointer to a) desired value.
1156         Ty = ByValType;
1157         break;
1158       case 3:
1159         // The fourth argument to GNU compare_exchange is a 'weak' flag.
1160         Ty = Context.BoolTy;
1161         break;
1162       }
1163     } else {
1164       // The order(s) are always converted to int.
1165       Ty = Context.IntTy;
1166     }
1167 
1168     InitializedEntity Entity =
1169         InitializedEntity::InitializeParameter(Context, Ty, false);
1170     ExprResult Arg = TheCall->getArg(i);
1171     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1172     if (Arg.isInvalid())
1173       return true;
1174     TheCall->setArg(i, Arg.get());
1175   }
1176 
1177   // Permute the arguments into a 'consistent' order.
1178   SmallVector<Expr*, 5> SubExprs;
1179   SubExprs.push_back(Ptr);
1180   switch (Form) {
1181   case Init:
1182     // Note, AtomicExpr::getVal1() has a special case for this atomic.
1183     SubExprs.push_back(TheCall->getArg(1)); // Val1
1184     break;
1185   case Load:
1186     SubExprs.push_back(TheCall->getArg(1)); // Order
1187     break;
1188   case Copy:
1189   case Arithmetic:
1190   case Xchg:
1191     SubExprs.push_back(TheCall->getArg(2)); // Order
1192     SubExprs.push_back(TheCall->getArg(1)); // Val1
1193     break;
1194   case GNUXchg:
1195     // Note, AtomicExpr::getVal2() has a special case for this atomic.
1196     SubExprs.push_back(TheCall->getArg(3)); // Order
1197     SubExprs.push_back(TheCall->getArg(1)); // Val1
1198     SubExprs.push_back(TheCall->getArg(2)); // Val2
1199     break;
1200   case C11CmpXchg:
1201     SubExprs.push_back(TheCall->getArg(3)); // Order
1202     SubExprs.push_back(TheCall->getArg(1)); // Val1
1203     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1204     SubExprs.push_back(TheCall->getArg(2)); // Val2
1205     break;
1206   case GNUCmpXchg:
1207     SubExprs.push_back(TheCall->getArg(4)); // Order
1208     SubExprs.push_back(TheCall->getArg(1)); // Val1
1209     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1210     SubExprs.push_back(TheCall->getArg(2)); // Val2
1211     SubExprs.push_back(TheCall->getArg(3)); // Weak
1212     break;
1213   }
1214 
1215   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1216                                             SubExprs, ResultType, Op,
1217                                             TheCall->getRParenLoc());
1218 
1219   if ((Op == AtomicExpr::AO__c11_atomic_load ||
1220        (Op == AtomicExpr::AO__c11_atomic_store)) &&
1221       Context.AtomicUsesUnsupportedLibcall(AE))
1222     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1223     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1224 
1225   return Owned(AE);
1226 }
1227 
1228 
1229 /// checkBuiltinArgument - Given a call to a builtin function, perform
1230 /// normal type-checking on the given argument, updating the call in
1231 /// place.  This is useful when a builtin function requires custom
1232 /// type-checking for some of its arguments but not necessarily all of
1233 /// them.
1234 ///
1235 /// Returns true on error.
1236 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1237   FunctionDecl *Fn = E->getDirectCallee();
1238   assert(Fn && "builtin call without direct callee!");
1239 
1240   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1241   InitializedEntity Entity =
1242     InitializedEntity::InitializeParameter(S.Context, Param);
1243 
1244   ExprResult Arg = E->getArg(0);
1245   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1246   if (Arg.isInvalid())
1247     return true;
1248 
1249   E->setArg(ArgIndex, Arg.take());
1250   return false;
1251 }
1252 
1253 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
1254 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
1255 /// type of its first argument.  The main ActOnCallExpr routines have already
1256 /// promoted the types of arguments because all of these calls are prototyped as
1257 /// void(...).
1258 ///
1259 /// This function goes through and does final semantic checking for these
1260 /// builtins,
1261 ExprResult
1262 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1263   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1264   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1265   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1266 
1267   // Ensure that we have at least one argument to do type inference from.
1268   if (TheCall->getNumArgs() < 1) {
1269     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1270       << 0 << 1 << TheCall->getNumArgs()
1271       << TheCall->getCallee()->getSourceRange();
1272     return ExprError();
1273   }
1274 
1275   // Inspect the first argument of the atomic builtin.  This should always be
1276   // a pointer type, whose element is an integral scalar or pointer type.
1277   // Because it is a pointer type, we don't have to worry about any implicit
1278   // casts here.
1279   // FIXME: We don't allow floating point scalars as input.
1280   Expr *FirstArg = TheCall->getArg(0);
1281   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1282   if (FirstArgResult.isInvalid())
1283     return ExprError();
1284   FirstArg = FirstArgResult.take();
1285   TheCall->setArg(0, FirstArg);
1286 
1287   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1288   if (!pointerType) {
1289     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1290       << FirstArg->getType() << FirstArg->getSourceRange();
1291     return ExprError();
1292   }
1293 
1294   QualType ValType = pointerType->getPointeeType();
1295   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1296       !ValType->isBlockPointerType()) {
1297     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1298       << FirstArg->getType() << FirstArg->getSourceRange();
1299     return ExprError();
1300   }
1301 
1302   switch (ValType.getObjCLifetime()) {
1303   case Qualifiers::OCL_None:
1304   case Qualifiers::OCL_ExplicitNone:
1305     // okay
1306     break;
1307 
1308   case Qualifiers::OCL_Weak:
1309   case Qualifiers::OCL_Strong:
1310   case Qualifiers::OCL_Autoreleasing:
1311     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1312       << ValType << FirstArg->getSourceRange();
1313     return ExprError();
1314   }
1315 
1316   // Strip any qualifiers off ValType.
1317   ValType = ValType.getUnqualifiedType();
1318 
1319   // The majority of builtins return a value, but a few have special return
1320   // types, so allow them to override appropriately below.
1321   QualType ResultType = ValType;
1322 
1323   // We need to figure out which concrete builtin this maps onto.  For example,
1324   // __sync_fetch_and_add with a 2 byte object turns into
1325   // __sync_fetch_and_add_2.
1326 #define BUILTIN_ROW(x) \
1327   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1328     Builtin::BI##x##_8, Builtin::BI##x##_16 }
1329 
1330   static const unsigned BuiltinIndices[][5] = {
1331     BUILTIN_ROW(__sync_fetch_and_add),
1332     BUILTIN_ROW(__sync_fetch_and_sub),
1333     BUILTIN_ROW(__sync_fetch_and_or),
1334     BUILTIN_ROW(__sync_fetch_and_and),
1335     BUILTIN_ROW(__sync_fetch_and_xor),
1336 
1337     BUILTIN_ROW(__sync_add_and_fetch),
1338     BUILTIN_ROW(__sync_sub_and_fetch),
1339     BUILTIN_ROW(__sync_and_and_fetch),
1340     BUILTIN_ROW(__sync_or_and_fetch),
1341     BUILTIN_ROW(__sync_xor_and_fetch),
1342 
1343     BUILTIN_ROW(__sync_val_compare_and_swap),
1344     BUILTIN_ROW(__sync_bool_compare_and_swap),
1345     BUILTIN_ROW(__sync_lock_test_and_set),
1346     BUILTIN_ROW(__sync_lock_release),
1347     BUILTIN_ROW(__sync_swap)
1348   };
1349 #undef BUILTIN_ROW
1350 
1351   // Determine the index of the size.
1352   unsigned SizeIndex;
1353   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1354   case 1: SizeIndex = 0; break;
1355   case 2: SizeIndex = 1; break;
1356   case 4: SizeIndex = 2; break;
1357   case 8: SizeIndex = 3; break;
1358   case 16: SizeIndex = 4; break;
1359   default:
1360     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1361       << FirstArg->getType() << FirstArg->getSourceRange();
1362     return ExprError();
1363   }
1364 
1365   // Each of these builtins has one pointer argument, followed by some number of
1366   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1367   // that we ignore.  Find out which row of BuiltinIndices to read from as well
1368   // as the number of fixed args.
1369   unsigned BuiltinID = FDecl->getBuiltinID();
1370   unsigned BuiltinIndex, NumFixed = 1;
1371   switch (BuiltinID) {
1372   default: llvm_unreachable("Unknown overloaded atomic builtin!");
1373   case Builtin::BI__sync_fetch_and_add:
1374   case Builtin::BI__sync_fetch_and_add_1:
1375   case Builtin::BI__sync_fetch_and_add_2:
1376   case Builtin::BI__sync_fetch_and_add_4:
1377   case Builtin::BI__sync_fetch_and_add_8:
1378   case Builtin::BI__sync_fetch_and_add_16:
1379     BuiltinIndex = 0;
1380     break;
1381 
1382   case Builtin::BI__sync_fetch_and_sub:
1383   case Builtin::BI__sync_fetch_and_sub_1:
1384   case Builtin::BI__sync_fetch_and_sub_2:
1385   case Builtin::BI__sync_fetch_and_sub_4:
1386   case Builtin::BI__sync_fetch_and_sub_8:
1387   case Builtin::BI__sync_fetch_and_sub_16:
1388     BuiltinIndex = 1;
1389     break;
1390 
1391   case Builtin::BI__sync_fetch_and_or:
1392   case Builtin::BI__sync_fetch_and_or_1:
1393   case Builtin::BI__sync_fetch_and_or_2:
1394   case Builtin::BI__sync_fetch_and_or_4:
1395   case Builtin::BI__sync_fetch_and_or_8:
1396   case Builtin::BI__sync_fetch_and_or_16:
1397     BuiltinIndex = 2;
1398     break;
1399 
1400   case Builtin::BI__sync_fetch_and_and:
1401   case Builtin::BI__sync_fetch_and_and_1:
1402   case Builtin::BI__sync_fetch_and_and_2:
1403   case Builtin::BI__sync_fetch_and_and_4:
1404   case Builtin::BI__sync_fetch_and_and_8:
1405   case Builtin::BI__sync_fetch_and_and_16:
1406     BuiltinIndex = 3;
1407     break;
1408 
1409   case Builtin::BI__sync_fetch_and_xor:
1410   case Builtin::BI__sync_fetch_and_xor_1:
1411   case Builtin::BI__sync_fetch_and_xor_2:
1412   case Builtin::BI__sync_fetch_and_xor_4:
1413   case Builtin::BI__sync_fetch_and_xor_8:
1414   case Builtin::BI__sync_fetch_and_xor_16:
1415     BuiltinIndex = 4;
1416     break;
1417 
1418   case Builtin::BI__sync_add_and_fetch:
1419   case Builtin::BI__sync_add_and_fetch_1:
1420   case Builtin::BI__sync_add_and_fetch_2:
1421   case Builtin::BI__sync_add_and_fetch_4:
1422   case Builtin::BI__sync_add_and_fetch_8:
1423   case Builtin::BI__sync_add_and_fetch_16:
1424     BuiltinIndex = 5;
1425     break;
1426 
1427   case Builtin::BI__sync_sub_and_fetch:
1428   case Builtin::BI__sync_sub_and_fetch_1:
1429   case Builtin::BI__sync_sub_and_fetch_2:
1430   case Builtin::BI__sync_sub_and_fetch_4:
1431   case Builtin::BI__sync_sub_and_fetch_8:
1432   case Builtin::BI__sync_sub_and_fetch_16:
1433     BuiltinIndex = 6;
1434     break;
1435 
1436   case Builtin::BI__sync_and_and_fetch:
1437   case Builtin::BI__sync_and_and_fetch_1:
1438   case Builtin::BI__sync_and_and_fetch_2:
1439   case Builtin::BI__sync_and_and_fetch_4:
1440   case Builtin::BI__sync_and_and_fetch_8:
1441   case Builtin::BI__sync_and_and_fetch_16:
1442     BuiltinIndex = 7;
1443     break;
1444 
1445   case Builtin::BI__sync_or_and_fetch:
1446   case Builtin::BI__sync_or_and_fetch_1:
1447   case Builtin::BI__sync_or_and_fetch_2:
1448   case Builtin::BI__sync_or_and_fetch_4:
1449   case Builtin::BI__sync_or_and_fetch_8:
1450   case Builtin::BI__sync_or_and_fetch_16:
1451     BuiltinIndex = 8;
1452     break;
1453 
1454   case Builtin::BI__sync_xor_and_fetch:
1455   case Builtin::BI__sync_xor_and_fetch_1:
1456   case Builtin::BI__sync_xor_and_fetch_2:
1457   case Builtin::BI__sync_xor_and_fetch_4:
1458   case Builtin::BI__sync_xor_and_fetch_8:
1459   case Builtin::BI__sync_xor_and_fetch_16:
1460     BuiltinIndex = 9;
1461     break;
1462 
1463   case Builtin::BI__sync_val_compare_and_swap:
1464   case Builtin::BI__sync_val_compare_and_swap_1:
1465   case Builtin::BI__sync_val_compare_and_swap_2:
1466   case Builtin::BI__sync_val_compare_and_swap_4:
1467   case Builtin::BI__sync_val_compare_and_swap_8:
1468   case Builtin::BI__sync_val_compare_and_swap_16:
1469     BuiltinIndex = 10;
1470     NumFixed = 2;
1471     break;
1472 
1473   case Builtin::BI__sync_bool_compare_and_swap:
1474   case Builtin::BI__sync_bool_compare_and_swap_1:
1475   case Builtin::BI__sync_bool_compare_and_swap_2:
1476   case Builtin::BI__sync_bool_compare_and_swap_4:
1477   case Builtin::BI__sync_bool_compare_and_swap_8:
1478   case Builtin::BI__sync_bool_compare_and_swap_16:
1479     BuiltinIndex = 11;
1480     NumFixed = 2;
1481     ResultType = Context.BoolTy;
1482     break;
1483 
1484   case Builtin::BI__sync_lock_test_and_set:
1485   case Builtin::BI__sync_lock_test_and_set_1:
1486   case Builtin::BI__sync_lock_test_and_set_2:
1487   case Builtin::BI__sync_lock_test_and_set_4:
1488   case Builtin::BI__sync_lock_test_and_set_8:
1489   case Builtin::BI__sync_lock_test_and_set_16:
1490     BuiltinIndex = 12;
1491     break;
1492 
1493   case Builtin::BI__sync_lock_release:
1494   case Builtin::BI__sync_lock_release_1:
1495   case Builtin::BI__sync_lock_release_2:
1496   case Builtin::BI__sync_lock_release_4:
1497   case Builtin::BI__sync_lock_release_8:
1498   case Builtin::BI__sync_lock_release_16:
1499     BuiltinIndex = 13;
1500     NumFixed = 0;
1501     ResultType = Context.VoidTy;
1502     break;
1503 
1504   case Builtin::BI__sync_swap:
1505   case Builtin::BI__sync_swap_1:
1506   case Builtin::BI__sync_swap_2:
1507   case Builtin::BI__sync_swap_4:
1508   case Builtin::BI__sync_swap_8:
1509   case Builtin::BI__sync_swap_16:
1510     BuiltinIndex = 14;
1511     break;
1512   }
1513 
1514   // Now that we know how many fixed arguments we expect, first check that we
1515   // have at least that many.
1516   if (TheCall->getNumArgs() < 1+NumFixed) {
1517     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1518       << 0 << 1+NumFixed << TheCall->getNumArgs()
1519       << TheCall->getCallee()->getSourceRange();
1520     return ExprError();
1521   }
1522 
1523   // Get the decl for the concrete builtin from this, we can tell what the
1524   // concrete integer type we should convert to is.
1525   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1526   const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1527   FunctionDecl *NewBuiltinDecl;
1528   if (NewBuiltinID == BuiltinID)
1529     NewBuiltinDecl = FDecl;
1530   else {
1531     // Perform builtin lookup to avoid redeclaring it.
1532     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1533     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1534     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1535     assert(Res.getFoundDecl());
1536     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1537     if (NewBuiltinDecl == 0)
1538       return ExprError();
1539   }
1540 
1541   // The first argument --- the pointer --- has a fixed type; we
1542   // deduce the types of the rest of the arguments accordingly.  Walk
1543   // the remaining arguments, converting them to the deduced value type.
1544   for (unsigned i = 0; i != NumFixed; ++i) {
1545     ExprResult Arg = TheCall->getArg(i+1);
1546 
1547     // GCC does an implicit conversion to the pointer or integer ValType.  This
1548     // can fail in some cases (1i -> int**), check for this error case now.
1549     // Initialize the argument.
1550     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1551                                                    ValType, /*consume*/ false);
1552     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1553     if (Arg.isInvalid())
1554       return ExprError();
1555 
1556     // Okay, we have something that *can* be converted to the right type.  Check
1557     // to see if there is a potentially weird extension going on here.  This can
1558     // happen when you do an atomic operation on something like an char* and
1559     // pass in 42.  The 42 gets converted to char.  This is even more strange
1560     // for things like 45.123 -> char, etc.
1561     // FIXME: Do this check.
1562     TheCall->setArg(i+1, Arg.take());
1563   }
1564 
1565   ASTContext& Context = this->getASTContext();
1566 
1567   // Create a new DeclRefExpr to refer to the new decl.
1568   DeclRefExpr* NewDRE = DeclRefExpr::Create(
1569       Context,
1570       DRE->getQualifierLoc(),
1571       SourceLocation(),
1572       NewBuiltinDecl,
1573       /*enclosing*/ false,
1574       DRE->getLocation(),
1575       Context.BuiltinFnTy,
1576       DRE->getValueKind());
1577 
1578   // Set the callee in the CallExpr.
1579   // FIXME: This loses syntactic information.
1580   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1581   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1582                                               CK_BuiltinFnToFnPtr);
1583   TheCall->setCallee(PromotedCall.take());
1584 
1585   // Change the result type of the call to match the original value type. This
1586   // is arbitrary, but the codegen for these builtins ins design to handle it
1587   // gracefully.
1588   TheCall->setType(ResultType);
1589 
1590   return TheCallResult;
1591 }
1592 
1593 /// CheckObjCString - Checks that the argument to the builtin
1594 /// CFString constructor is correct
1595 /// Note: It might also make sense to do the UTF-16 conversion here (would
1596 /// simplify the backend).
1597 bool Sema::CheckObjCString(Expr *Arg) {
1598   Arg = Arg->IgnoreParenCasts();
1599   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1600 
1601   if (!Literal || !Literal->isAscii()) {
1602     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1603       << Arg->getSourceRange();
1604     return true;
1605   }
1606 
1607   if (Literal->containsNonAsciiOrNull()) {
1608     StringRef String = Literal->getString();
1609     unsigned NumBytes = String.size();
1610     SmallVector<UTF16, 128> ToBuf(NumBytes);
1611     const UTF8 *FromPtr = (const UTF8 *)String.data();
1612     UTF16 *ToPtr = &ToBuf[0];
1613 
1614     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1615                                                  &ToPtr, ToPtr + NumBytes,
1616                                                  strictConversion);
1617     // Check for conversion failure.
1618     if (Result != conversionOK)
1619       Diag(Arg->getLocStart(),
1620            diag::warn_cfstring_truncated) << Arg->getSourceRange();
1621   }
1622   return false;
1623 }
1624 
1625 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1626 /// Emit an error and return true on failure, return false on success.
1627 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1628   Expr *Fn = TheCall->getCallee();
1629   if (TheCall->getNumArgs() > 2) {
1630     Diag(TheCall->getArg(2)->getLocStart(),
1631          diag::err_typecheck_call_too_many_args)
1632       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1633       << Fn->getSourceRange()
1634       << SourceRange(TheCall->getArg(2)->getLocStart(),
1635                      (*(TheCall->arg_end()-1))->getLocEnd());
1636     return true;
1637   }
1638 
1639   if (TheCall->getNumArgs() < 2) {
1640     return Diag(TheCall->getLocEnd(),
1641       diag::err_typecheck_call_too_few_args_at_least)
1642       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1643   }
1644 
1645   // Type-check the first argument normally.
1646   if (checkBuiltinArgument(*this, TheCall, 0))
1647     return true;
1648 
1649   // Determine whether the current function is variadic or not.
1650   BlockScopeInfo *CurBlock = getCurBlock();
1651   bool isVariadic;
1652   if (CurBlock)
1653     isVariadic = CurBlock->TheDecl->isVariadic();
1654   else if (FunctionDecl *FD = getCurFunctionDecl())
1655     isVariadic = FD->isVariadic();
1656   else
1657     isVariadic = getCurMethodDecl()->isVariadic();
1658 
1659   if (!isVariadic) {
1660     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1661     return true;
1662   }
1663 
1664   // Verify that the second argument to the builtin is the last argument of the
1665   // current function or method.
1666   bool SecondArgIsLastNamedArgument = false;
1667   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1668 
1669   // These are valid if SecondArgIsLastNamedArgument is false after the next
1670   // block.
1671   QualType Type;
1672   SourceLocation ParamLoc;
1673 
1674   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1675     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1676       // FIXME: This isn't correct for methods (results in bogus warning).
1677       // Get the last formal in the current function.
1678       const ParmVarDecl *LastArg;
1679       if (CurBlock)
1680         LastArg = *(CurBlock->TheDecl->param_end()-1);
1681       else if (FunctionDecl *FD = getCurFunctionDecl())
1682         LastArg = *(FD->param_end()-1);
1683       else
1684         LastArg = *(getCurMethodDecl()->param_end()-1);
1685       SecondArgIsLastNamedArgument = PV == LastArg;
1686 
1687       Type = PV->getType();
1688       ParamLoc = PV->getLocation();
1689     }
1690   }
1691 
1692   if (!SecondArgIsLastNamedArgument)
1693     Diag(TheCall->getArg(1)->getLocStart(),
1694          diag::warn_second_parameter_of_va_start_not_last_named_argument);
1695   else if (Type->isReferenceType()) {
1696     Diag(Arg->getLocStart(),
1697          diag::warn_va_start_of_reference_type_is_undefined);
1698     Diag(ParamLoc, diag::note_parameter_type) << Type;
1699   }
1700 
1701   TheCall->setType(Context.VoidTy);
1702   return false;
1703 }
1704 
1705 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1706 /// friends.  This is declared to take (...), so we have to check everything.
1707 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1708   if (TheCall->getNumArgs() < 2)
1709     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1710       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
1711   if (TheCall->getNumArgs() > 2)
1712     return Diag(TheCall->getArg(2)->getLocStart(),
1713                 diag::err_typecheck_call_too_many_args)
1714       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1715       << SourceRange(TheCall->getArg(2)->getLocStart(),
1716                      (*(TheCall->arg_end()-1))->getLocEnd());
1717 
1718   ExprResult OrigArg0 = TheCall->getArg(0);
1719   ExprResult OrigArg1 = TheCall->getArg(1);
1720 
1721   // Do standard promotions between the two arguments, returning their common
1722   // type.
1723   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
1724   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1725     return true;
1726 
1727   // Make sure any conversions are pushed back into the call; this is
1728   // type safe since unordered compare builtins are declared as "_Bool
1729   // foo(...)".
1730   TheCall->setArg(0, OrigArg0.get());
1731   TheCall->setArg(1, OrigArg1.get());
1732 
1733   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
1734     return false;
1735 
1736   // If the common type isn't a real floating type, then the arguments were
1737   // invalid for this operation.
1738   if (Res.isNull() || !Res->isRealFloatingType())
1739     return Diag(OrigArg0.get()->getLocStart(),
1740                 diag::err_typecheck_call_invalid_ordered_compare)
1741       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1742       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
1743 
1744   return false;
1745 }
1746 
1747 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1748 /// __builtin_isnan and friends.  This is declared to take (...), so we have
1749 /// to check everything. We expect the last argument to be a floating point
1750 /// value.
1751 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1752   if (TheCall->getNumArgs() < NumArgs)
1753     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1754       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1755   if (TheCall->getNumArgs() > NumArgs)
1756     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1757                 diag::err_typecheck_call_too_many_args)
1758       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1759       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1760                      (*(TheCall->arg_end()-1))->getLocEnd());
1761 
1762   Expr *OrigArg = TheCall->getArg(NumArgs-1);
1763 
1764   if (OrigArg->isTypeDependent())
1765     return false;
1766 
1767   // This operation requires a non-_Complex floating-point number.
1768   if (!OrigArg->getType()->isRealFloatingType())
1769     return Diag(OrigArg->getLocStart(),
1770                 diag::err_typecheck_call_invalid_unary_fp)
1771       << OrigArg->getType() << OrigArg->getSourceRange();
1772 
1773   // If this is an implicit conversion from float -> double, remove it.
1774   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1775     Expr *CastArg = Cast->getSubExpr();
1776     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1777       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1778              "promotion from float to double is the only expected cast here");
1779       Cast->setSubExpr(0);
1780       TheCall->setArg(NumArgs-1, CastArg);
1781     }
1782   }
1783 
1784   return false;
1785 }
1786 
1787 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1788 // This is declared to take (...), so we have to check everything.
1789 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1790   if (TheCall->getNumArgs() < 2)
1791     return ExprError(Diag(TheCall->getLocEnd(),
1792                           diag::err_typecheck_call_too_few_args_at_least)
1793                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1794                      << TheCall->getSourceRange());
1795 
1796   // Determine which of the following types of shufflevector we're checking:
1797   // 1) unary, vector mask: (lhs, mask)
1798   // 2) binary, vector mask: (lhs, rhs, mask)
1799   // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1800   QualType resType = TheCall->getArg(0)->getType();
1801   unsigned numElements = 0;
1802 
1803   if (!TheCall->getArg(0)->isTypeDependent() &&
1804       !TheCall->getArg(1)->isTypeDependent()) {
1805     QualType LHSType = TheCall->getArg(0)->getType();
1806     QualType RHSType = TheCall->getArg(1)->getType();
1807 
1808     if (!LHSType->isVectorType() || !RHSType->isVectorType())
1809       return ExprError(Diag(TheCall->getLocStart(),
1810                             diag::err_shufflevector_non_vector)
1811                        << SourceRange(TheCall->getArg(0)->getLocStart(),
1812                                       TheCall->getArg(1)->getLocEnd()));
1813 
1814     numElements = LHSType->getAs<VectorType>()->getNumElements();
1815     unsigned numResElements = TheCall->getNumArgs() - 2;
1816 
1817     // Check to see if we have a call with 2 vector arguments, the unary shuffle
1818     // with mask.  If so, verify that RHS is an integer vector type with the
1819     // same number of elts as lhs.
1820     if (TheCall->getNumArgs() == 2) {
1821       if (!RHSType->hasIntegerRepresentation() ||
1822           RHSType->getAs<VectorType>()->getNumElements() != numElements)
1823         return ExprError(Diag(TheCall->getLocStart(),
1824                               diag::err_shufflevector_incompatible_vector)
1825                          << SourceRange(TheCall->getArg(1)->getLocStart(),
1826                                         TheCall->getArg(1)->getLocEnd()));
1827     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1828       return ExprError(Diag(TheCall->getLocStart(),
1829                             diag::err_shufflevector_incompatible_vector)
1830                        << SourceRange(TheCall->getArg(0)->getLocStart(),
1831                                       TheCall->getArg(1)->getLocEnd()));
1832     } else if (numElements != numResElements) {
1833       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1834       resType = Context.getVectorType(eltType, numResElements,
1835                                       VectorType::GenericVector);
1836     }
1837   }
1838 
1839   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1840     if (TheCall->getArg(i)->isTypeDependent() ||
1841         TheCall->getArg(i)->isValueDependent())
1842       continue;
1843 
1844     llvm::APSInt Result(32);
1845     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1846       return ExprError(Diag(TheCall->getLocStart(),
1847                             diag::err_shufflevector_nonconstant_argument)
1848                        << TheCall->getArg(i)->getSourceRange());
1849 
1850     // Allow -1 which will be translated to undef in the IR.
1851     if (Result.isSigned() && Result.isAllOnesValue())
1852       continue;
1853 
1854     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1855       return ExprError(Diag(TheCall->getLocStart(),
1856                             diag::err_shufflevector_argument_too_large)
1857                        << TheCall->getArg(i)->getSourceRange());
1858   }
1859 
1860   SmallVector<Expr*, 32> exprs;
1861 
1862   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1863     exprs.push_back(TheCall->getArg(i));
1864     TheCall->setArg(i, 0);
1865   }
1866 
1867   return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
1868                                             TheCall->getCallee()->getLocStart(),
1869                                             TheCall->getRParenLoc()));
1870 }
1871 
1872 /// SemaConvertVectorExpr - Handle __builtin_convertvector
1873 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1874                                        SourceLocation BuiltinLoc,
1875                                        SourceLocation RParenLoc) {
1876   ExprValueKind VK = VK_RValue;
1877   ExprObjectKind OK = OK_Ordinary;
1878   QualType DstTy = TInfo->getType();
1879   QualType SrcTy = E->getType();
1880 
1881   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1882     return ExprError(Diag(BuiltinLoc,
1883                           diag::err_convertvector_non_vector)
1884                      << E->getSourceRange());
1885   if (!DstTy->isVectorType() && !DstTy->isDependentType())
1886     return ExprError(Diag(BuiltinLoc,
1887                           diag::err_convertvector_non_vector_type));
1888 
1889   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1890     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1891     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1892     if (SrcElts != DstElts)
1893       return ExprError(Diag(BuiltinLoc,
1894                             diag::err_convertvector_incompatible_vector)
1895                        << E->getSourceRange());
1896   }
1897 
1898   return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1899                BuiltinLoc, RParenLoc));
1900 
1901 }
1902 
1903 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1904 // This is declared to take (const void*, ...) and can take two
1905 // optional constant int args.
1906 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1907   unsigned NumArgs = TheCall->getNumArgs();
1908 
1909   if (NumArgs > 3)
1910     return Diag(TheCall->getLocEnd(),
1911              diag::err_typecheck_call_too_many_args_at_most)
1912              << 0 /*function call*/ << 3 << NumArgs
1913              << TheCall->getSourceRange();
1914 
1915   // Argument 0 is checked for us and the remaining arguments must be
1916   // constant integers.
1917   for (unsigned i = 1; i != NumArgs; ++i) {
1918     Expr *Arg = TheCall->getArg(i);
1919 
1920     // We can't check the value of a dependent argument.
1921     if (Arg->isTypeDependent() || Arg->isValueDependent())
1922       continue;
1923 
1924     llvm::APSInt Result;
1925     if (SemaBuiltinConstantArg(TheCall, i, Result))
1926       return true;
1927 
1928     // FIXME: gcc issues a warning and rewrites these to 0. These
1929     // seems especially odd for the third argument since the default
1930     // is 3.
1931     if (i == 1) {
1932       if (Result.getLimitedValue() > 1)
1933         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1934              << "0" << "1" << Arg->getSourceRange();
1935     } else {
1936       if (Result.getLimitedValue() > 3)
1937         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1938             << "0" << "3" << Arg->getSourceRange();
1939     }
1940   }
1941 
1942   return false;
1943 }
1944 
1945 /// SemaBuiltinMMPrefetch - Handle _mm_prefetch.
1946 // This is declared to take (const char*, int)
1947 bool Sema::SemaBuiltinMMPrefetch(CallExpr *TheCall) {
1948   Expr *Arg = TheCall->getArg(1);
1949 
1950   // We can't check the value of a dependent argument.
1951   if (Arg->isTypeDependent() || Arg->isValueDependent())
1952     return false;
1953 
1954   llvm::APSInt Result;
1955   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1956     return true;
1957 
1958   if (Result.getLimitedValue() > 3)
1959     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1960         << "0" << "3" << Arg->getSourceRange();
1961 
1962   return false;
1963 }
1964 
1965 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1966 /// TheCall is a constant expression.
1967 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1968                                   llvm::APSInt &Result) {
1969   Expr *Arg = TheCall->getArg(ArgNum);
1970   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1971   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1972 
1973   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1974 
1975   if (!Arg->isIntegerConstantExpr(Result, Context))
1976     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1977                 << FDecl->getDeclName() <<  Arg->getSourceRange();
1978 
1979   return false;
1980 }
1981 
1982 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1983 /// int type). This simply type checks that type is one of the defined
1984 /// constants (0-3).
1985 // For compatibility check 0-3, llvm only handles 0 and 2.
1986 bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1987   llvm::APSInt Result;
1988 
1989   // We can't check the value of a dependent argument.
1990   if (TheCall->getArg(1)->isTypeDependent() ||
1991       TheCall->getArg(1)->isValueDependent())
1992     return false;
1993 
1994   // Check constant-ness first.
1995   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1996     return true;
1997 
1998   Expr *Arg = TheCall->getArg(1);
1999   if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
2000     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2001              << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2002   }
2003 
2004   return false;
2005 }
2006 
2007 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
2008 /// This checks that val is a constant 1.
2009 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2010   Expr *Arg = TheCall->getArg(1);
2011   llvm::APSInt Result;
2012 
2013   // TODO: This is less than ideal. Overload this to take a value.
2014   if (SemaBuiltinConstantArg(TheCall, 1, Result))
2015     return true;
2016 
2017   if (Result != 1)
2018     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2019              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2020 
2021   return false;
2022 }
2023 
2024 namespace {
2025 enum StringLiteralCheckType {
2026   SLCT_NotALiteral,
2027   SLCT_UncheckedLiteral,
2028   SLCT_CheckedLiteral
2029 };
2030 }
2031 
2032 // Determine if an expression is a string literal or constant string.
2033 // If this function returns false on the arguments to a function expecting a
2034 // format string, we will usually need to emit a warning.
2035 // True string literals are then checked by CheckFormatString.
2036 static StringLiteralCheckType
2037 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2038                       bool HasVAListArg, unsigned format_idx,
2039                       unsigned firstDataArg, Sema::FormatStringType Type,
2040                       Sema::VariadicCallType CallType, bool InFunctionCall,
2041                       llvm::SmallBitVector &CheckedVarArgs) {
2042  tryAgain:
2043   if (E->isTypeDependent() || E->isValueDependent())
2044     return SLCT_NotALiteral;
2045 
2046   E = E->IgnoreParenCasts();
2047 
2048   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
2049     // Technically -Wformat-nonliteral does not warn about this case.
2050     // The behavior of printf and friends in this case is implementation
2051     // dependent.  Ideally if the format string cannot be null then
2052     // it should have a 'nonnull' attribute in the function prototype.
2053     return SLCT_UncheckedLiteral;
2054 
2055   switch (E->getStmtClass()) {
2056   case Stmt::BinaryConditionalOperatorClass:
2057   case Stmt::ConditionalOperatorClass: {
2058     // The expression is a literal if both sub-expressions were, and it was
2059     // completely checked only if both sub-expressions were checked.
2060     const AbstractConditionalOperator *C =
2061         cast<AbstractConditionalOperator>(E);
2062     StringLiteralCheckType Left =
2063         checkFormatStringExpr(S, C->getTrueExpr(), Args,
2064                               HasVAListArg, format_idx, firstDataArg,
2065                               Type, CallType, InFunctionCall, CheckedVarArgs);
2066     if (Left == SLCT_NotALiteral)
2067       return SLCT_NotALiteral;
2068     StringLiteralCheckType Right =
2069         checkFormatStringExpr(S, C->getFalseExpr(), Args,
2070                               HasVAListArg, format_idx, firstDataArg,
2071                               Type, CallType, InFunctionCall, CheckedVarArgs);
2072     return Left < Right ? Left : Right;
2073   }
2074 
2075   case Stmt::ImplicitCastExprClass: {
2076     E = cast<ImplicitCastExpr>(E)->getSubExpr();
2077     goto tryAgain;
2078   }
2079 
2080   case Stmt::OpaqueValueExprClass:
2081     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2082       E = src;
2083       goto tryAgain;
2084     }
2085     return SLCT_NotALiteral;
2086 
2087   case Stmt::PredefinedExprClass:
2088     // While __func__, etc., are technically not string literals, they
2089     // cannot contain format specifiers and thus are not a security
2090     // liability.
2091     return SLCT_UncheckedLiteral;
2092 
2093   case Stmt::DeclRefExprClass: {
2094     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
2095 
2096     // As an exception, do not flag errors for variables binding to
2097     // const string literals.
2098     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2099       bool isConstant = false;
2100       QualType T = DR->getType();
2101 
2102       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2103         isConstant = AT->getElementType().isConstant(S.Context);
2104       } else if (const PointerType *PT = T->getAs<PointerType>()) {
2105         isConstant = T.isConstant(S.Context) &&
2106                      PT->getPointeeType().isConstant(S.Context);
2107       } else if (T->isObjCObjectPointerType()) {
2108         // In ObjC, there is usually no "const ObjectPointer" type,
2109         // so don't check if the pointee type is constant.
2110         isConstant = T.isConstant(S.Context);
2111       }
2112 
2113       if (isConstant) {
2114         if (const Expr *Init = VD->getAnyInitializer()) {
2115           // Look through initializers like const char c[] = { "foo" }
2116           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2117             if (InitList->isStringLiteralInit())
2118               Init = InitList->getInit(0)->IgnoreParenImpCasts();
2119           }
2120           return checkFormatStringExpr(S, Init, Args,
2121                                        HasVAListArg, format_idx,
2122                                        firstDataArg, Type, CallType,
2123                                        /*InFunctionCall*/false, CheckedVarArgs);
2124         }
2125       }
2126 
2127       // For vprintf* functions (i.e., HasVAListArg==true), we add a
2128       // special check to see if the format string is a function parameter
2129       // of the function calling the printf function.  If the function
2130       // has an attribute indicating it is a printf-like function, then we
2131       // should suppress warnings concerning non-literals being used in a call
2132       // to a vprintf function.  For example:
2133       //
2134       // void
2135       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2136       //      va_list ap;
2137       //      va_start(ap, fmt);
2138       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
2139       //      ...
2140       // }
2141       if (HasVAListArg) {
2142         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2143           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2144             int PVIndex = PV->getFunctionScopeIndex() + 1;
2145             for (specific_attr_iterator<FormatAttr>
2146                  i = ND->specific_attr_begin<FormatAttr>(),
2147                  e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2148               FormatAttr *PVFormat = *i;
2149               // adjust for implicit parameter
2150               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2151                 if (MD->isInstance())
2152                   ++PVIndex;
2153               // We also check if the formats are compatible.
2154               // We can't pass a 'scanf' string to a 'printf' function.
2155               if (PVIndex == PVFormat->getFormatIdx() &&
2156                   Type == S.GetFormatStringType(PVFormat))
2157                 return SLCT_UncheckedLiteral;
2158             }
2159           }
2160         }
2161       }
2162     }
2163 
2164     return SLCT_NotALiteral;
2165   }
2166 
2167   case Stmt::CallExprClass:
2168   case Stmt::CXXMemberCallExprClass: {
2169     const CallExpr *CE = cast<CallExpr>(E);
2170     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2171       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2172         unsigned ArgIndex = FA->getFormatIdx();
2173         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2174           if (MD->isInstance())
2175             --ArgIndex;
2176         const Expr *Arg = CE->getArg(ArgIndex - 1);
2177 
2178         return checkFormatStringExpr(S, Arg, Args,
2179                                      HasVAListArg, format_idx, firstDataArg,
2180                                      Type, CallType, InFunctionCall,
2181                                      CheckedVarArgs);
2182       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2183         unsigned BuiltinID = FD->getBuiltinID();
2184         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2185             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2186           const Expr *Arg = CE->getArg(0);
2187           return checkFormatStringExpr(S, Arg, Args,
2188                                        HasVAListArg, format_idx,
2189                                        firstDataArg, Type, CallType,
2190                                        InFunctionCall, CheckedVarArgs);
2191         }
2192       }
2193     }
2194 
2195     return SLCT_NotALiteral;
2196   }
2197   case Stmt::ObjCStringLiteralClass:
2198   case Stmt::StringLiteralClass: {
2199     const StringLiteral *StrE = NULL;
2200 
2201     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
2202       StrE = ObjCFExpr->getString();
2203     else
2204       StrE = cast<StringLiteral>(E);
2205 
2206     if (StrE) {
2207       S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2208                           Type, InFunctionCall, CallType, CheckedVarArgs);
2209       return SLCT_CheckedLiteral;
2210     }
2211 
2212     return SLCT_NotALiteral;
2213   }
2214 
2215   default:
2216     return SLCT_NotALiteral;
2217   }
2218 }
2219 
2220 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2221   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
2222   .Case("scanf", FST_Scanf)
2223   .Cases("printf", "printf0", FST_Printf)
2224   .Cases("NSString", "CFString", FST_NSString)
2225   .Case("strftime", FST_Strftime)
2226   .Case("strfmon", FST_Strfmon)
2227   .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2228   .Default(FST_Unknown);
2229 }
2230 
2231 /// CheckFormatArguments - Check calls to printf and scanf (and similar
2232 /// functions) for correct use of format strings.
2233 /// Returns true if a format string has been fully checked.
2234 bool Sema::CheckFormatArguments(const FormatAttr *Format,
2235                                 ArrayRef<const Expr *> Args,
2236                                 bool IsCXXMember,
2237                                 VariadicCallType CallType,
2238                                 SourceLocation Loc, SourceRange Range,
2239                                 llvm::SmallBitVector &CheckedVarArgs) {
2240   FormatStringInfo FSI;
2241   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
2242     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
2243                                 FSI.FirstDataArg, GetFormatStringType(Format),
2244                                 CallType, Loc, Range, CheckedVarArgs);
2245   return false;
2246 }
2247 
2248 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
2249                                 bool HasVAListArg, unsigned format_idx,
2250                                 unsigned firstDataArg, FormatStringType Type,
2251                                 VariadicCallType CallType,
2252                                 SourceLocation Loc, SourceRange Range,
2253                                 llvm::SmallBitVector &CheckedVarArgs) {
2254   // CHECK: printf/scanf-like function is called with no format string.
2255   if (format_idx >= Args.size()) {
2256     Diag(Loc, diag::warn_missing_format_string) << Range;
2257     return false;
2258   }
2259 
2260   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
2261 
2262   // CHECK: format string is not a string literal.
2263   //
2264   // Dynamically generated format strings are difficult to
2265   // automatically vet at compile time.  Requiring that format strings
2266   // are string literals: (1) permits the checking of format strings by
2267   // the compiler and thereby (2) can practically remove the source of
2268   // many format string exploits.
2269 
2270   // Format string can be either ObjC string (e.g. @"%d") or
2271   // C string (e.g. "%d")
2272   // ObjC string uses the same format specifiers as C string, so we can use
2273   // the same format string checking logic for both ObjC and C strings.
2274   StringLiteralCheckType CT =
2275       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2276                             format_idx, firstDataArg, Type, CallType,
2277                             /*IsFunctionCall*/true, CheckedVarArgs);
2278   if (CT != SLCT_NotALiteral)
2279     // Literal format string found, check done!
2280     return CT == SLCT_CheckedLiteral;
2281 
2282   // Strftime is particular as it always uses a single 'time' argument,
2283   // so it is safe to pass a non-literal string.
2284   if (Type == FST_Strftime)
2285     return false;
2286 
2287   // Do not emit diag when the string param is a macro expansion and the
2288   // format is either NSString or CFString. This is a hack to prevent
2289   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2290   // which are usually used in place of NS and CF string literals.
2291   if (Type == FST_NSString &&
2292       SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
2293     return false;
2294 
2295   // If there are no arguments specified, warn with -Wformat-security, otherwise
2296   // warn only with -Wformat-nonliteral.
2297   if (Args.size() == firstDataArg)
2298     Diag(Args[format_idx]->getLocStart(),
2299          diag::warn_format_nonliteral_noargs)
2300       << OrigFormatExpr->getSourceRange();
2301   else
2302     Diag(Args[format_idx]->getLocStart(),
2303          diag::warn_format_nonliteral)
2304            << OrigFormatExpr->getSourceRange();
2305   return false;
2306 }
2307 
2308 namespace {
2309 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2310 protected:
2311   Sema &S;
2312   const StringLiteral *FExpr;
2313   const Expr *OrigFormatExpr;
2314   const unsigned FirstDataArg;
2315   const unsigned NumDataArgs;
2316   const char *Beg; // Start of format string.
2317   const bool HasVAListArg;
2318   ArrayRef<const Expr *> Args;
2319   unsigned FormatIdx;
2320   llvm::SmallBitVector CoveredArgs;
2321   bool usesPositionalArgs;
2322   bool atFirstArg;
2323   bool inFunctionCall;
2324   Sema::VariadicCallType CallType;
2325   llvm::SmallBitVector &CheckedVarArgs;
2326 public:
2327   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
2328                      const Expr *origFormatExpr, unsigned firstDataArg,
2329                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
2330                      ArrayRef<const Expr *> Args,
2331                      unsigned formatIdx, bool inFunctionCall,
2332                      Sema::VariadicCallType callType,
2333                      llvm::SmallBitVector &CheckedVarArgs)
2334     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
2335       FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2336       Beg(beg), HasVAListArg(hasVAListArg),
2337       Args(Args), FormatIdx(formatIdx),
2338       usesPositionalArgs(false), atFirstArg(true),
2339       inFunctionCall(inFunctionCall), CallType(callType),
2340       CheckedVarArgs(CheckedVarArgs) {
2341     CoveredArgs.resize(numDataArgs);
2342     CoveredArgs.reset();
2343   }
2344 
2345   void DoneProcessing();
2346 
2347   void HandleIncompleteSpecifier(const char *startSpecifier,
2348                                  unsigned specifierLen);
2349 
2350   void HandleInvalidLengthModifier(
2351       const analyze_format_string::FormatSpecifier &FS,
2352       const analyze_format_string::ConversionSpecifier &CS,
2353       const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
2354 
2355   void HandleNonStandardLengthModifier(
2356       const analyze_format_string::FormatSpecifier &FS,
2357       const char *startSpecifier, unsigned specifierLen);
2358 
2359   void HandleNonStandardConversionSpecifier(
2360       const analyze_format_string::ConversionSpecifier &CS,
2361       const char *startSpecifier, unsigned specifierLen);
2362 
2363   virtual void HandlePosition(const char *startPos, unsigned posLen);
2364 
2365   virtual void HandleInvalidPosition(const char *startSpecifier,
2366                                      unsigned specifierLen,
2367                                      analyze_format_string::PositionContext p);
2368 
2369   virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2370 
2371   void HandleNullChar(const char *nullCharacter);
2372 
2373   template <typename Range>
2374   static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2375                                    const Expr *ArgumentExpr,
2376                                    PartialDiagnostic PDiag,
2377                                    SourceLocation StringLoc,
2378                                    bool IsStringLocation, Range StringRange,
2379                                    ArrayRef<FixItHint> Fixit = None);
2380 
2381 protected:
2382   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2383                                         const char *startSpec,
2384                                         unsigned specifierLen,
2385                                         const char *csStart, unsigned csLen);
2386 
2387   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2388                                          const char *startSpec,
2389                                          unsigned specifierLen);
2390 
2391   SourceRange getFormatStringRange();
2392   CharSourceRange getSpecifierRange(const char *startSpecifier,
2393                                     unsigned specifierLen);
2394   SourceLocation getLocationOfByte(const char *x);
2395 
2396   const Expr *getDataArg(unsigned i) const;
2397 
2398   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2399                     const analyze_format_string::ConversionSpecifier &CS,
2400                     const char *startSpecifier, unsigned specifierLen,
2401                     unsigned argIndex);
2402 
2403   template <typename Range>
2404   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2405                             bool IsStringLocation, Range StringRange,
2406                             ArrayRef<FixItHint> Fixit = None);
2407 
2408   void CheckPositionalAndNonpositionalArgs(
2409       const analyze_format_string::FormatSpecifier *FS);
2410 };
2411 }
2412 
2413 SourceRange CheckFormatHandler::getFormatStringRange() {
2414   return OrigFormatExpr->getSourceRange();
2415 }
2416 
2417 CharSourceRange CheckFormatHandler::
2418 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
2419   SourceLocation Start = getLocationOfByte(startSpecifier);
2420   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
2421 
2422   // Advance the end SourceLocation by one due to half-open ranges.
2423   End = End.getLocWithOffset(1);
2424 
2425   return CharSourceRange::getCharRange(Start, End);
2426 }
2427 
2428 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
2429   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
2430 }
2431 
2432 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2433                                                    unsigned specifierLen){
2434   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2435                        getLocationOfByte(startSpecifier),
2436                        /*IsStringLocation*/true,
2437                        getSpecifierRange(startSpecifier, specifierLen));
2438 }
2439 
2440 void CheckFormatHandler::HandleInvalidLengthModifier(
2441     const analyze_format_string::FormatSpecifier &FS,
2442     const analyze_format_string::ConversionSpecifier &CS,
2443     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
2444   using namespace analyze_format_string;
2445 
2446   const LengthModifier &LM = FS.getLengthModifier();
2447   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2448 
2449   // See if we know how to fix this length modifier.
2450   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2451   if (FixedLM) {
2452     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2453                          getLocationOfByte(LM.getStart()),
2454                          /*IsStringLocation*/true,
2455                          getSpecifierRange(startSpecifier, specifierLen));
2456 
2457     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2458       << FixedLM->toString()
2459       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2460 
2461   } else {
2462     FixItHint Hint;
2463     if (DiagID == diag::warn_format_nonsensical_length)
2464       Hint = FixItHint::CreateRemoval(LMRange);
2465 
2466     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2467                          getLocationOfByte(LM.getStart()),
2468                          /*IsStringLocation*/true,
2469                          getSpecifierRange(startSpecifier, specifierLen),
2470                          Hint);
2471   }
2472 }
2473 
2474 void CheckFormatHandler::HandleNonStandardLengthModifier(
2475     const analyze_format_string::FormatSpecifier &FS,
2476     const char *startSpecifier, unsigned specifierLen) {
2477   using namespace analyze_format_string;
2478 
2479   const LengthModifier &LM = FS.getLengthModifier();
2480   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2481 
2482   // See if we know how to fix this length modifier.
2483   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2484   if (FixedLM) {
2485     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2486                            << LM.toString() << 0,
2487                          getLocationOfByte(LM.getStart()),
2488                          /*IsStringLocation*/true,
2489                          getSpecifierRange(startSpecifier, specifierLen));
2490 
2491     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2492       << FixedLM->toString()
2493       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2494 
2495   } else {
2496     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2497                            << LM.toString() << 0,
2498                          getLocationOfByte(LM.getStart()),
2499                          /*IsStringLocation*/true,
2500                          getSpecifierRange(startSpecifier, specifierLen));
2501   }
2502 }
2503 
2504 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2505     const analyze_format_string::ConversionSpecifier &CS,
2506     const char *startSpecifier, unsigned specifierLen) {
2507   using namespace analyze_format_string;
2508 
2509   // See if we know how to fix this conversion specifier.
2510   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2511   if (FixedCS) {
2512     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2513                           << CS.toString() << /*conversion specifier*/1,
2514                          getLocationOfByte(CS.getStart()),
2515                          /*IsStringLocation*/true,
2516                          getSpecifierRange(startSpecifier, specifierLen));
2517 
2518     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2519     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2520       << FixedCS->toString()
2521       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2522   } else {
2523     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2524                           << CS.toString() << /*conversion specifier*/1,
2525                          getLocationOfByte(CS.getStart()),
2526                          /*IsStringLocation*/true,
2527                          getSpecifierRange(startSpecifier, specifierLen));
2528   }
2529 }
2530 
2531 void CheckFormatHandler::HandlePosition(const char *startPos,
2532                                         unsigned posLen) {
2533   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2534                                getLocationOfByte(startPos),
2535                                /*IsStringLocation*/true,
2536                                getSpecifierRange(startPos, posLen));
2537 }
2538 
2539 void
2540 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2541                                      analyze_format_string::PositionContext p) {
2542   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2543                          << (unsigned) p,
2544                        getLocationOfByte(startPos), /*IsStringLocation*/true,
2545                        getSpecifierRange(startPos, posLen));
2546 }
2547 
2548 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
2549                                             unsigned posLen) {
2550   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2551                                getLocationOfByte(startPos),
2552                                /*IsStringLocation*/true,
2553                                getSpecifierRange(startPos, posLen));
2554 }
2555 
2556 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
2557   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
2558     // The presence of a null character is likely an error.
2559     EmitFormatDiagnostic(
2560       S.PDiag(diag::warn_printf_format_string_contains_null_char),
2561       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2562       getFormatStringRange());
2563   }
2564 }
2565 
2566 // Note that this may return NULL if there was an error parsing or building
2567 // one of the argument expressions.
2568 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
2569   return Args[FirstDataArg + i];
2570 }
2571 
2572 void CheckFormatHandler::DoneProcessing() {
2573     // Does the number of data arguments exceed the number of
2574     // format conversions in the format string?
2575   if (!HasVAListArg) {
2576       // Find any arguments that weren't covered.
2577     CoveredArgs.flip();
2578     signed notCoveredArg = CoveredArgs.find_first();
2579     if (notCoveredArg >= 0) {
2580       assert((unsigned)notCoveredArg < NumDataArgs);
2581       if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2582         SourceLocation Loc = E->getLocStart();
2583         if (!S.getSourceManager().isInSystemMacro(Loc)) {
2584           EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2585                                Loc, /*IsStringLocation*/false,
2586                                getFormatStringRange());
2587         }
2588       }
2589     }
2590   }
2591 }
2592 
2593 bool
2594 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2595                                                      SourceLocation Loc,
2596                                                      const char *startSpec,
2597                                                      unsigned specifierLen,
2598                                                      const char *csStart,
2599                                                      unsigned csLen) {
2600 
2601   bool keepGoing = true;
2602   if (argIndex < NumDataArgs) {
2603     // Consider the argument coverered, even though the specifier doesn't
2604     // make sense.
2605     CoveredArgs.set(argIndex);
2606   }
2607   else {
2608     // If argIndex exceeds the number of data arguments we
2609     // don't issue a warning because that is just a cascade of warnings (and
2610     // they may have intended '%%' anyway). We don't want to continue processing
2611     // the format string after this point, however, as we will like just get
2612     // gibberish when trying to match arguments.
2613     keepGoing = false;
2614   }
2615 
2616   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2617                          << StringRef(csStart, csLen),
2618                        Loc, /*IsStringLocation*/true,
2619                        getSpecifierRange(startSpec, specifierLen));
2620 
2621   return keepGoing;
2622 }
2623 
2624 void
2625 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2626                                                       const char *startSpec,
2627                                                       unsigned specifierLen) {
2628   EmitFormatDiagnostic(
2629     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2630     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2631 }
2632 
2633 bool
2634 CheckFormatHandler::CheckNumArgs(
2635   const analyze_format_string::FormatSpecifier &FS,
2636   const analyze_format_string::ConversionSpecifier &CS,
2637   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2638 
2639   if (argIndex >= NumDataArgs) {
2640     PartialDiagnostic PDiag = FS.usesPositionalArg()
2641       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2642            << (argIndex+1) << NumDataArgs)
2643       : S.PDiag(diag::warn_printf_insufficient_data_args);
2644     EmitFormatDiagnostic(
2645       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2646       getSpecifierRange(startSpecifier, specifierLen));
2647     return false;
2648   }
2649   return true;
2650 }
2651 
2652 template<typename Range>
2653 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2654                                               SourceLocation Loc,
2655                                               bool IsStringLocation,
2656                                               Range StringRange,
2657                                               ArrayRef<FixItHint> FixIt) {
2658   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
2659                        Loc, IsStringLocation, StringRange, FixIt);
2660 }
2661 
2662 /// \brief If the format string is not within the funcion call, emit a note
2663 /// so that the function call and string are in diagnostic messages.
2664 ///
2665 /// \param InFunctionCall if true, the format string is within the function
2666 /// call and only one diagnostic message will be produced.  Otherwise, an
2667 /// extra note will be emitted pointing to location of the format string.
2668 ///
2669 /// \param ArgumentExpr the expression that is passed as the format string
2670 /// argument in the function call.  Used for getting locations when two
2671 /// diagnostics are emitted.
2672 ///
2673 /// \param PDiag the callee should already have provided any strings for the
2674 /// diagnostic message.  This function only adds locations and fixits
2675 /// to diagnostics.
2676 ///
2677 /// \param Loc primary location for diagnostic.  If two diagnostics are
2678 /// required, one will be at Loc and a new SourceLocation will be created for
2679 /// the other one.
2680 ///
2681 /// \param IsStringLocation if true, Loc points to the format string should be
2682 /// used for the note.  Otherwise, Loc points to the argument list and will
2683 /// be used with PDiag.
2684 ///
2685 /// \param StringRange some or all of the string to highlight.  This is
2686 /// templated so it can accept either a CharSourceRange or a SourceRange.
2687 ///
2688 /// \param FixIt optional fix it hint for the format string.
2689 template<typename Range>
2690 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2691                                               const Expr *ArgumentExpr,
2692                                               PartialDiagnostic PDiag,
2693                                               SourceLocation Loc,
2694                                               bool IsStringLocation,
2695                                               Range StringRange,
2696                                               ArrayRef<FixItHint> FixIt) {
2697   if (InFunctionCall) {
2698     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2699     D << StringRange;
2700     for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2701          I != E; ++I) {
2702       D << *I;
2703     }
2704   } else {
2705     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2706       << ArgumentExpr->getSourceRange();
2707 
2708     const Sema::SemaDiagnosticBuilder &Note =
2709       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2710              diag::note_format_string_defined);
2711 
2712     Note << StringRange;
2713     for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2714          I != E; ++I) {
2715       Note << *I;
2716     }
2717   }
2718 }
2719 
2720 //===--- CHECK: Printf format string checking ------------------------------===//
2721 
2722 namespace {
2723 class CheckPrintfHandler : public CheckFormatHandler {
2724   bool ObjCContext;
2725 public:
2726   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2727                      const Expr *origFormatExpr, unsigned firstDataArg,
2728                      unsigned numDataArgs, bool isObjC,
2729                      const char *beg, bool hasVAListArg,
2730                      ArrayRef<const Expr *> Args,
2731                      unsigned formatIdx, bool inFunctionCall,
2732                      Sema::VariadicCallType CallType,
2733                      llvm::SmallBitVector &CheckedVarArgs)
2734     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2735                          numDataArgs, beg, hasVAListArg, Args,
2736                          formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2737       ObjCContext(isObjC)
2738   {}
2739 
2740 
2741   bool HandleInvalidPrintfConversionSpecifier(
2742                                       const analyze_printf::PrintfSpecifier &FS,
2743                                       const char *startSpecifier,
2744                                       unsigned specifierLen);
2745 
2746   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2747                              const char *startSpecifier,
2748                              unsigned specifierLen);
2749   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2750                        const char *StartSpecifier,
2751                        unsigned SpecifierLen,
2752                        const Expr *E);
2753 
2754   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2755                     const char *startSpecifier, unsigned specifierLen);
2756   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2757                            const analyze_printf::OptionalAmount &Amt,
2758                            unsigned type,
2759                            const char *startSpecifier, unsigned specifierLen);
2760   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2761                   const analyze_printf::OptionalFlag &flag,
2762                   const char *startSpecifier, unsigned specifierLen);
2763   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2764                          const analyze_printf::OptionalFlag &ignoredFlag,
2765                          const analyze_printf::OptionalFlag &flag,
2766                          const char *startSpecifier, unsigned specifierLen);
2767   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
2768                            const Expr *E);
2769 
2770 };
2771 }
2772 
2773 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2774                                       const analyze_printf::PrintfSpecifier &FS,
2775                                       const char *startSpecifier,
2776                                       unsigned specifierLen) {
2777   const analyze_printf::PrintfConversionSpecifier &CS =
2778     FS.getConversionSpecifier();
2779 
2780   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2781                                           getLocationOfByte(CS.getStart()),
2782                                           startSpecifier, specifierLen,
2783                                           CS.getStart(), CS.getLength());
2784 }
2785 
2786 bool CheckPrintfHandler::HandleAmount(
2787                                const analyze_format_string::OptionalAmount &Amt,
2788                                unsigned k, const char *startSpecifier,
2789                                unsigned specifierLen) {
2790 
2791   if (Amt.hasDataArgument()) {
2792     if (!HasVAListArg) {
2793       unsigned argIndex = Amt.getArgIndex();
2794       if (argIndex >= NumDataArgs) {
2795         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2796                                << k,
2797                              getLocationOfByte(Amt.getStart()),
2798                              /*IsStringLocation*/true,
2799                              getSpecifierRange(startSpecifier, specifierLen));
2800         // Don't do any more checking.  We will just emit
2801         // spurious errors.
2802         return false;
2803       }
2804 
2805       // Type check the data argument.  It should be an 'int'.
2806       // Although not in conformance with C99, we also allow the argument to be
2807       // an 'unsigned int' as that is a reasonably safe case.  GCC also
2808       // doesn't emit a warning for that case.
2809       CoveredArgs.set(argIndex);
2810       const Expr *Arg = getDataArg(argIndex);
2811       if (!Arg)
2812         return false;
2813 
2814       QualType T = Arg->getType();
2815 
2816       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2817       assert(AT.isValid());
2818 
2819       if (!AT.matchesType(S.Context, T)) {
2820         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
2821                                << k << AT.getRepresentativeTypeName(S.Context)
2822                                << T << Arg->getSourceRange(),
2823                              getLocationOfByte(Amt.getStart()),
2824                              /*IsStringLocation*/true,
2825                              getSpecifierRange(startSpecifier, specifierLen));
2826         // Don't do any more checking.  We will just emit
2827         // spurious errors.
2828         return false;
2829       }
2830     }
2831   }
2832   return true;
2833 }
2834 
2835 void CheckPrintfHandler::HandleInvalidAmount(
2836                                       const analyze_printf::PrintfSpecifier &FS,
2837                                       const analyze_printf::OptionalAmount &Amt,
2838                                       unsigned type,
2839                                       const char *startSpecifier,
2840                                       unsigned specifierLen) {
2841   const analyze_printf::PrintfConversionSpecifier &CS =
2842     FS.getConversionSpecifier();
2843 
2844   FixItHint fixit =
2845     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2846       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2847                                  Amt.getConstantLength()))
2848       : FixItHint();
2849 
2850   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2851                          << type << CS.toString(),
2852                        getLocationOfByte(Amt.getStart()),
2853                        /*IsStringLocation*/true,
2854                        getSpecifierRange(startSpecifier, specifierLen),
2855                        fixit);
2856 }
2857 
2858 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2859                                     const analyze_printf::OptionalFlag &flag,
2860                                     const char *startSpecifier,
2861                                     unsigned specifierLen) {
2862   // Warn about pointless flag with a fixit removal.
2863   const analyze_printf::PrintfConversionSpecifier &CS =
2864     FS.getConversionSpecifier();
2865   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2866                          << flag.toString() << CS.toString(),
2867                        getLocationOfByte(flag.getPosition()),
2868                        /*IsStringLocation*/true,
2869                        getSpecifierRange(startSpecifier, specifierLen),
2870                        FixItHint::CreateRemoval(
2871                          getSpecifierRange(flag.getPosition(), 1)));
2872 }
2873 
2874 void CheckPrintfHandler::HandleIgnoredFlag(
2875                                 const analyze_printf::PrintfSpecifier &FS,
2876                                 const analyze_printf::OptionalFlag &ignoredFlag,
2877                                 const analyze_printf::OptionalFlag &flag,
2878                                 const char *startSpecifier,
2879                                 unsigned specifierLen) {
2880   // Warn about ignored flag with a fixit removal.
2881   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2882                          << ignoredFlag.toString() << flag.toString(),
2883                        getLocationOfByte(ignoredFlag.getPosition()),
2884                        /*IsStringLocation*/true,
2885                        getSpecifierRange(startSpecifier, specifierLen),
2886                        FixItHint::CreateRemoval(
2887                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
2888 }
2889 
2890 // Determines if the specified is a C++ class or struct containing
2891 // a member with the specified name and kind (e.g. a CXXMethodDecl named
2892 // "c_str()").
2893 template<typename MemberKind>
2894 static llvm::SmallPtrSet<MemberKind*, 1>
2895 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2896   const RecordType *RT = Ty->getAs<RecordType>();
2897   llvm::SmallPtrSet<MemberKind*, 1> Results;
2898 
2899   if (!RT)
2900     return Results;
2901   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2902   if (!RD || !RD->getDefinition())
2903     return Results;
2904 
2905   LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2906                  Sema::LookupMemberName);
2907   R.suppressDiagnostics();
2908 
2909   // We just need to include all members of the right kind turned up by the
2910   // filter, at this point.
2911   if (S.LookupQualifiedName(R, RT->getDecl()))
2912     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2913       NamedDecl *decl = (*I)->getUnderlyingDecl();
2914       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2915         Results.insert(FK);
2916     }
2917   return Results;
2918 }
2919 
2920 /// Check if we could call '.c_str()' on an object.
2921 ///
2922 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2923 /// allow the call, or if it would be ambiguous).
2924 bool Sema::hasCStrMethod(const Expr *E) {
2925   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2926   MethodSet Results =
2927       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2928   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2929        MI != ME; ++MI)
2930     if ((*MI)->getMinRequiredArguments() == 0)
2931       return true;
2932   return false;
2933 }
2934 
2935 // Check if a (w)string was passed when a (w)char* was needed, and offer a
2936 // better diagnostic if so. AT is assumed to be valid.
2937 // Returns true when a c_str() conversion method is found.
2938 bool CheckPrintfHandler::checkForCStrMembers(
2939     const analyze_printf::ArgType &AT, const Expr *E) {
2940   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2941 
2942   MethodSet Results =
2943       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2944 
2945   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2946        MI != ME; ++MI) {
2947     const CXXMethodDecl *Method = *MI;
2948     if (Method->getMinRequiredArguments() == 0 &&
2949         AT.matchesType(S.Context, Method->getReturnType())) {
2950       // FIXME: Suggest parens if the expression needs them.
2951       SourceLocation EndLoc =
2952           S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2953       S.Diag(E->getLocStart(), diag::note_printf_c_str)
2954           << "c_str()"
2955           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2956       return true;
2957     }
2958   }
2959 
2960   return false;
2961 }
2962 
2963 bool
2964 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
2965                                             &FS,
2966                                           const char *startSpecifier,
2967                                           unsigned specifierLen) {
2968 
2969   using namespace analyze_format_string;
2970   using namespace analyze_printf;
2971   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
2972 
2973   if (FS.consumesDataArgument()) {
2974     if (atFirstArg) {
2975         atFirstArg = false;
2976         usesPositionalArgs = FS.usesPositionalArg();
2977     }
2978     else if (usesPositionalArgs != FS.usesPositionalArg()) {
2979       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2980                                         startSpecifier, specifierLen);
2981       return false;
2982     }
2983   }
2984 
2985   // First check if the field width, precision, and conversion specifier
2986   // have matching data arguments.
2987   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2988                     startSpecifier, specifierLen)) {
2989     return false;
2990   }
2991 
2992   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2993                     startSpecifier, specifierLen)) {
2994     return false;
2995   }
2996 
2997   if (!CS.consumesDataArgument()) {
2998     // FIXME: Technically specifying a precision or field width here
2999     // makes no sense.  Worth issuing a warning at some point.
3000     return true;
3001   }
3002 
3003   // Consume the argument.
3004   unsigned argIndex = FS.getArgIndex();
3005   if (argIndex < NumDataArgs) {
3006     // The check to see if the argIndex is valid will come later.
3007     // We set the bit here because we may exit early from this
3008     // function if we encounter some other error.
3009     CoveredArgs.set(argIndex);
3010   }
3011 
3012   // Check for using an Objective-C specific conversion specifier
3013   // in a non-ObjC literal.
3014   if (!ObjCContext && CS.isObjCArg()) {
3015     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3016                                                   specifierLen);
3017   }
3018 
3019   // Check for invalid use of field width
3020   if (!FS.hasValidFieldWidth()) {
3021     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
3022         startSpecifier, specifierLen);
3023   }
3024 
3025   // Check for invalid use of precision
3026   if (!FS.hasValidPrecision()) {
3027     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3028         startSpecifier, specifierLen);
3029   }
3030 
3031   // Check each flag does not conflict with any other component.
3032   if (!FS.hasValidThousandsGroupingPrefix())
3033     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
3034   if (!FS.hasValidLeadingZeros())
3035     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3036   if (!FS.hasValidPlusPrefix())
3037     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
3038   if (!FS.hasValidSpacePrefix())
3039     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
3040   if (!FS.hasValidAlternativeForm())
3041     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3042   if (!FS.hasValidLeftJustified())
3043     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3044 
3045   // Check that flags are not ignored by another flag
3046   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3047     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3048         startSpecifier, specifierLen);
3049   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3050     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3051             startSpecifier, specifierLen);
3052 
3053   // Check the length modifier is valid with the given conversion specifier.
3054   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3055     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3056                                 diag::warn_format_nonsensical_length);
3057   else if (!FS.hasStandardLengthModifier())
3058     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3059   else if (!FS.hasStandardLengthConversionCombination())
3060     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3061                                 diag::warn_format_non_standard_conversion_spec);
3062 
3063   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3064     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3065 
3066   // The remaining checks depend on the data arguments.
3067   if (HasVAListArg)
3068     return true;
3069 
3070   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3071     return false;
3072 
3073   const Expr *Arg = getDataArg(argIndex);
3074   if (!Arg)
3075     return true;
3076 
3077   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
3078 }
3079 
3080 static bool requiresParensToAddCast(const Expr *E) {
3081   // FIXME: We should have a general way to reason about operator
3082   // precedence and whether parens are actually needed here.
3083   // Take care of a few common cases where they aren't.
3084   const Expr *Inside = E->IgnoreImpCasts();
3085   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3086     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3087 
3088   switch (Inside->getStmtClass()) {
3089   case Stmt::ArraySubscriptExprClass:
3090   case Stmt::CallExprClass:
3091   case Stmt::CharacterLiteralClass:
3092   case Stmt::CXXBoolLiteralExprClass:
3093   case Stmt::DeclRefExprClass:
3094   case Stmt::FloatingLiteralClass:
3095   case Stmt::IntegerLiteralClass:
3096   case Stmt::MemberExprClass:
3097   case Stmt::ObjCArrayLiteralClass:
3098   case Stmt::ObjCBoolLiteralExprClass:
3099   case Stmt::ObjCBoxedExprClass:
3100   case Stmt::ObjCDictionaryLiteralClass:
3101   case Stmt::ObjCEncodeExprClass:
3102   case Stmt::ObjCIvarRefExprClass:
3103   case Stmt::ObjCMessageExprClass:
3104   case Stmt::ObjCPropertyRefExprClass:
3105   case Stmt::ObjCStringLiteralClass:
3106   case Stmt::ObjCSubscriptRefExprClass:
3107   case Stmt::ParenExprClass:
3108   case Stmt::StringLiteralClass:
3109   case Stmt::UnaryOperatorClass:
3110     return false;
3111   default:
3112     return true;
3113   }
3114 }
3115 
3116 bool
3117 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3118                                     const char *StartSpecifier,
3119                                     unsigned SpecifierLen,
3120                                     const Expr *E) {
3121   using namespace analyze_format_string;
3122   using namespace analyze_printf;
3123   // Now type check the data expression that matches the
3124   // format specifier.
3125   const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3126                                                     ObjCContext);
3127   if (!AT.isValid())
3128     return true;
3129 
3130   QualType ExprTy = E->getType();
3131   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3132     ExprTy = TET->getUnderlyingExpr()->getType();
3133   }
3134 
3135   if (AT.matchesType(S.Context, ExprTy))
3136     return true;
3137 
3138   // Look through argument promotions for our error message's reported type.
3139   // This includes the integral and floating promotions, but excludes array
3140   // and function pointer decay; seeing that an argument intended to be a
3141   // string has type 'char [6]' is probably more confusing than 'char *'.
3142   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3143     if (ICE->getCastKind() == CK_IntegralCast ||
3144         ICE->getCastKind() == CK_FloatingCast) {
3145       E = ICE->getSubExpr();
3146       ExprTy = E->getType();
3147 
3148       // Check if we didn't match because of an implicit cast from a 'char'
3149       // or 'short' to an 'int'.  This is done because printf is a varargs
3150       // function.
3151       if (ICE->getType() == S.Context.IntTy ||
3152           ICE->getType() == S.Context.UnsignedIntTy) {
3153         // All further checking is done on the subexpression.
3154         if (AT.matchesType(S.Context, ExprTy))
3155           return true;
3156       }
3157     }
3158   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3159     // Special case for 'a', which has type 'int' in C.
3160     // Note, however, that we do /not/ want to treat multibyte constants like
3161     // 'MooV' as characters! This form is deprecated but still exists.
3162     if (ExprTy == S.Context.IntTy)
3163       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3164         ExprTy = S.Context.CharTy;
3165   }
3166 
3167   // %C in an Objective-C context prints a unichar, not a wchar_t.
3168   // If the argument is an integer of some kind, believe the %C and suggest
3169   // a cast instead of changing the conversion specifier.
3170   QualType IntendedTy = ExprTy;
3171   if (ObjCContext &&
3172       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3173     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3174         !ExprTy->isCharType()) {
3175       // 'unichar' is defined as a typedef of unsigned short, but we should
3176       // prefer using the typedef if it is visible.
3177       IntendedTy = S.Context.UnsignedShortTy;
3178 
3179       // While we are here, check if the value is an IntegerLiteral that happens
3180       // to be within the valid range.
3181       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3182         const llvm::APInt &V = IL->getValue();
3183         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3184           return true;
3185       }
3186 
3187       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3188                           Sema::LookupOrdinaryName);
3189       if (S.LookupName(Result, S.getCurScope())) {
3190         NamedDecl *ND = Result.getFoundDecl();
3191         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3192           if (TD->getUnderlyingType() == IntendedTy)
3193             IntendedTy = S.Context.getTypedefType(TD);
3194       }
3195     }
3196   }
3197 
3198   // Special-case some of Darwin's platform-independence types by suggesting
3199   // casts to primitive types that are known to be large enough.
3200   bool ShouldNotPrintDirectly = false;
3201   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
3202     // Use a 'while' to peel off layers of typedefs.
3203     QualType TyTy = IntendedTy;
3204     while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3205       StringRef Name = UserTy->getDecl()->getName();
3206       QualType CastTy = llvm::StringSwitch<QualType>(Name)
3207         .Case("NSInteger", S.Context.LongTy)
3208         .Case("NSUInteger", S.Context.UnsignedLongTy)
3209         .Case("SInt32", S.Context.IntTy)
3210         .Case("UInt32", S.Context.UnsignedIntTy)
3211         .Default(QualType());
3212 
3213       if (!CastTy.isNull()) {
3214         ShouldNotPrintDirectly = true;
3215         IntendedTy = CastTy;
3216         break;
3217       }
3218       TyTy = UserTy->desugar();
3219     }
3220   }
3221 
3222   // We may be able to offer a FixItHint if it is a supported type.
3223   PrintfSpecifier fixedFS = FS;
3224   bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
3225                                  S.Context, ObjCContext);
3226 
3227   if (success) {
3228     // Get the fix string from the fixed format specifier
3229     SmallString<16> buf;
3230     llvm::raw_svector_ostream os(buf);
3231     fixedFS.toString(os);
3232 
3233     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3234 
3235     if (IntendedTy == ExprTy) {
3236       // In this case, the specifier is wrong and should be changed to match
3237       // the argument.
3238       EmitFormatDiagnostic(
3239         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3240           << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3241           << E->getSourceRange(),
3242         E->getLocStart(),
3243         /*IsStringLocation*/false,
3244         SpecRange,
3245         FixItHint::CreateReplacement(SpecRange, os.str()));
3246 
3247     } else {
3248       // The canonical type for formatting this value is different from the
3249       // actual type of the expression. (This occurs, for example, with Darwin's
3250       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3251       // should be printed as 'long' for 64-bit compatibility.)
3252       // Rather than emitting a normal format/argument mismatch, we want to
3253       // add a cast to the recommended type (and correct the format string
3254       // if necessary).
3255       SmallString<16> CastBuf;
3256       llvm::raw_svector_ostream CastFix(CastBuf);
3257       CastFix << "(";
3258       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3259       CastFix << ")";
3260 
3261       SmallVector<FixItHint,4> Hints;
3262       if (!AT.matchesType(S.Context, IntendedTy))
3263         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3264 
3265       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3266         // If there's already a cast present, just replace it.
3267         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3268         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3269 
3270       } else if (!requiresParensToAddCast(E)) {
3271         // If the expression has high enough precedence,
3272         // just write the C-style cast.
3273         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3274                                                    CastFix.str()));
3275       } else {
3276         // Otherwise, add parens around the expression as well as the cast.
3277         CastFix << "(";
3278         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3279                                                    CastFix.str()));
3280 
3281         SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3282         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3283       }
3284 
3285       if (ShouldNotPrintDirectly) {
3286         // The expression has a type that should not be printed directly.
3287         // We extract the name from the typedef because we don't want to show
3288         // the underlying type in the diagnostic.
3289         StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
3290 
3291         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3292                                << Name << IntendedTy
3293                                << E->getSourceRange(),
3294                              E->getLocStart(), /*IsStringLocation=*/false,
3295                              SpecRange, Hints);
3296       } else {
3297         // In this case, the expression could be printed using a different
3298         // specifier, but we've decided that the specifier is probably correct
3299         // and we should cast instead. Just use the normal warning message.
3300         EmitFormatDiagnostic(
3301           S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3302             << AT.getRepresentativeTypeName(S.Context) << ExprTy
3303             << E->getSourceRange(),
3304           E->getLocStart(), /*IsStringLocation*/false,
3305           SpecRange, Hints);
3306       }
3307     }
3308   } else {
3309     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3310                                                    SpecifierLen);
3311     // Since the warning for passing non-POD types to variadic functions
3312     // was deferred until now, we emit a warning for non-POD
3313     // arguments here.
3314     switch (S.isValidVarArgType(ExprTy)) {
3315     case Sema::VAK_Valid:
3316     case Sema::VAK_ValidInCXX11:
3317       EmitFormatDiagnostic(
3318         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3319           << AT.getRepresentativeTypeName(S.Context) << ExprTy
3320           << CSR
3321           << E->getSourceRange(),
3322         E->getLocStart(), /*IsStringLocation*/false, CSR);
3323       break;
3324 
3325     case Sema::VAK_Undefined:
3326       EmitFormatDiagnostic(
3327         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
3328           << S.getLangOpts().CPlusPlus11
3329           << ExprTy
3330           << CallType
3331           << AT.getRepresentativeTypeName(S.Context)
3332           << CSR
3333           << E->getSourceRange(),
3334         E->getLocStart(), /*IsStringLocation*/false, CSR);
3335       checkForCStrMembers(AT, E);
3336       break;
3337 
3338     case Sema::VAK_Invalid:
3339       if (ExprTy->isObjCObjectType())
3340         EmitFormatDiagnostic(
3341           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3342             << S.getLangOpts().CPlusPlus11
3343             << ExprTy
3344             << CallType
3345             << AT.getRepresentativeTypeName(S.Context)
3346             << CSR
3347             << E->getSourceRange(),
3348           E->getLocStart(), /*IsStringLocation*/false, CSR);
3349       else
3350         // FIXME: If this is an initializer list, suggest removing the braces
3351         // or inserting a cast to the target type.
3352         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3353           << isa<InitListExpr>(E) << ExprTy << CallType
3354           << AT.getRepresentativeTypeName(S.Context)
3355           << E->getSourceRange();
3356       break;
3357     }
3358 
3359     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3360            "format string specifier index out of range");
3361     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
3362   }
3363 
3364   return true;
3365 }
3366 
3367 //===--- CHECK: Scanf format string checking ------------------------------===//
3368 
3369 namespace {
3370 class CheckScanfHandler : public CheckFormatHandler {
3371 public:
3372   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3373                     const Expr *origFormatExpr, unsigned firstDataArg,
3374                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
3375                     ArrayRef<const Expr *> Args,
3376                     unsigned formatIdx, bool inFunctionCall,
3377                     Sema::VariadicCallType CallType,
3378                     llvm::SmallBitVector &CheckedVarArgs)
3379     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3380                          numDataArgs, beg, hasVAListArg,
3381                          Args, formatIdx, inFunctionCall, CallType,
3382                          CheckedVarArgs)
3383   {}
3384 
3385   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3386                             const char *startSpecifier,
3387                             unsigned specifierLen);
3388 
3389   bool HandleInvalidScanfConversionSpecifier(
3390           const analyze_scanf::ScanfSpecifier &FS,
3391           const char *startSpecifier,
3392           unsigned specifierLen);
3393 
3394   void HandleIncompleteScanList(const char *start, const char *end);
3395 };
3396 }
3397 
3398 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3399                                                  const char *end) {
3400   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3401                        getLocationOfByte(end), /*IsStringLocation*/true,
3402                        getSpecifierRange(start, end - start));
3403 }
3404 
3405 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3406                                         const analyze_scanf::ScanfSpecifier &FS,
3407                                         const char *startSpecifier,
3408                                         unsigned specifierLen) {
3409 
3410   const analyze_scanf::ScanfConversionSpecifier &CS =
3411     FS.getConversionSpecifier();
3412 
3413   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3414                                           getLocationOfByte(CS.getStart()),
3415                                           startSpecifier, specifierLen,
3416                                           CS.getStart(), CS.getLength());
3417 }
3418 
3419 bool CheckScanfHandler::HandleScanfSpecifier(
3420                                        const analyze_scanf::ScanfSpecifier &FS,
3421                                        const char *startSpecifier,
3422                                        unsigned specifierLen) {
3423 
3424   using namespace analyze_scanf;
3425   using namespace analyze_format_string;
3426 
3427   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
3428 
3429   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
3430   // be used to decide if we are using positional arguments consistently.
3431   if (FS.consumesDataArgument()) {
3432     if (atFirstArg) {
3433       atFirstArg = false;
3434       usesPositionalArgs = FS.usesPositionalArg();
3435     }
3436     else if (usesPositionalArgs != FS.usesPositionalArg()) {
3437       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3438                                         startSpecifier, specifierLen);
3439       return false;
3440     }
3441   }
3442 
3443   // Check if the field with is non-zero.
3444   const OptionalAmount &Amt = FS.getFieldWidth();
3445   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3446     if (Amt.getConstantAmount() == 0) {
3447       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3448                                                    Amt.getConstantLength());
3449       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3450                            getLocationOfByte(Amt.getStart()),
3451                            /*IsStringLocation*/true, R,
3452                            FixItHint::CreateRemoval(R));
3453     }
3454   }
3455 
3456   if (!FS.consumesDataArgument()) {
3457     // FIXME: Technically specifying a precision or field width here
3458     // makes no sense.  Worth issuing a warning at some point.
3459     return true;
3460   }
3461 
3462   // Consume the argument.
3463   unsigned argIndex = FS.getArgIndex();
3464   if (argIndex < NumDataArgs) {
3465       // The check to see if the argIndex is valid will come later.
3466       // We set the bit here because we may exit early from this
3467       // function if we encounter some other error.
3468     CoveredArgs.set(argIndex);
3469   }
3470 
3471   // Check the length modifier is valid with the given conversion specifier.
3472   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3473     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3474                                 diag::warn_format_nonsensical_length);
3475   else if (!FS.hasStandardLengthModifier())
3476     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3477   else if (!FS.hasStandardLengthConversionCombination())
3478     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3479                                 diag::warn_format_non_standard_conversion_spec);
3480 
3481   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3482     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3483 
3484   // The remaining checks depend on the data arguments.
3485   if (HasVAListArg)
3486     return true;
3487 
3488   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3489     return false;
3490 
3491   // Check that the argument type matches the format specifier.
3492   const Expr *Ex = getDataArg(argIndex);
3493   if (!Ex)
3494     return true;
3495 
3496   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3497   if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
3498     ScanfSpecifier fixedFS = FS;
3499     bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
3500                                    S.Context);
3501 
3502     if (success) {
3503       // Get the fix string from the fixed format specifier.
3504       SmallString<128> buf;
3505       llvm::raw_svector_ostream os(buf);
3506       fixedFS.toString(os);
3507 
3508       EmitFormatDiagnostic(
3509         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3510           << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3511           << Ex->getSourceRange(),
3512         Ex->getLocStart(),
3513         /*IsStringLocation*/false,
3514         getSpecifierRange(startSpecifier, specifierLen),
3515         FixItHint::CreateReplacement(
3516           getSpecifierRange(startSpecifier, specifierLen),
3517           os.str()));
3518     } else {
3519       EmitFormatDiagnostic(
3520         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3521           << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3522           << Ex->getSourceRange(),
3523         Ex->getLocStart(),
3524         /*IsStringLocation*/false,
3525         getSpecifierRange(startSpecifier, specifierLen));
3526     }
3527   }
3528 
3529   return true;
3530 }
3531 
3532 void Sema::CheckFormatString(const StringLiteral *FExpr,
3533                              const Expr *OrigFormatExpr,
3534                              ArrayRef<const Expr *> Args,
3535                              bool HasVAListArg, unsigned format_idx,
3536                              unsigned firstDataArg, FormatStringType Type,
3537                              bool inFunctionCall, VariadicCallType CallType,
3538                              llvm::SmallBitVector &CheckedVarArgs) {
3539 
3540   // CHECK: is the format string a wide literal?
3541   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
3542     CheckFormatHandler::EmitFormatDiagnostic(
3543       *this, inFunctionCall, Args[format_idx],
3544       PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3545       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3546     return;
3547   }
3548 
3549   // Str - The format string.  NOTE: this is NOT null-terminated!
3550   StringRef StrRef = FExpr->getString();
3551   const char *Str = StrRef.data();
3552   // Account for cases where the string literal is truncated in a declaration.
3553   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3554   assert(T && "String literal not of constant array type!");
3555   size_t TypeSize = T->getSize().getZExtValue();
3556   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
3557   const unsigned numDataArgs = Args.size() - firstDataArg;
3558 
3559   // Emit a warning if the string literal is truncated and does not contain an
3560   // embedded null character.
3561   if (TypeSize <= StrRef.size() &&
3562       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3563     CheckFormatHandler::EmitFormatDiagnostic(
3564         *this, inFunctionCall, Args[format_idx],
3565         PDiag(diag::warn_printf_format_string_not_null_terminated),
3566         FExpr->getLocStart(),
3567         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3568     return;
3569   }
3570 
3571   // CHECK: empty format string?
3572   if (StrLen == 0 && numDataArgs > 0) {
3573     CheckFormatHandler::EmitFormatDiagnostic(
3574       *this, inFunctionCall, Args[format_idx],
3575       PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3576       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3577     return;
3578   }
3579 
3580   if (Type == FST_Printf || Type == FST_NSString) {
3581     CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
3582                          numDataArgs, (Type == FST_NSString),
3583                          Str, HasVAListArg, Args, format_idx,
3584                          inFunctionCall, CallType, CheckedVarArgs);
3585 
3586     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
3587                                                   getLangOpts(),
3588                                                   Context.getTargetInfo()))
3589       H.DoneProcessing();
3590   } else if (Type == FST_Scanf) {
3591     CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
3592                         Str, HasVAListArg, Args, format_idx,
3593                         inFunctionCall, CallType, CheckedVarArgs);
3594 
3595     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
3596                                                  getLangOpts(),
3597                                                  Context.getTargetInfo()))
3598       H.DoneProcessing();
3599   } // TODO: handle other formats
3600 }
3601 
3602 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3603 
3604 // Returns the related absolute value function that is larger, of 0 if one
3605 // does not exist.
3606 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3607   switch (AbsFunction) {
3608   default:
3609     return 0;
3610 
3611   case Builtin::BI__builtin_abs:
3612     return Builtin::BI__builtin_labs;
3613   case Builtin::BI__builtin_labs:
3614     return Builtin::BI__builtin_llabs;
3615   case Builtin::BI__builtin_llabs:
3616     return 0;
3617 
3618   case Builtin::BI__builtin_fabsf:
3619     return Builtin::BI__builtin_fabs;
3620   case Builtin::BI__builtin_fabs:
3621     return Builtin::BI__builtin_fabsl;
3622   case Builtin::BI__builtin_fabsl:
3623     return 0;
3624 
3625   case Builtin::BI__builtin_cabsf:
3626     return Builtin::BI__builtin_cabs;
3627   case Builtin::BI__builtin_cabs:
3628     return Builtin::BI__builtin_cabsl;
3629   case Builtin::BI__builtin_cabsl:
3630     return 0;
3631 
3632   case Builtin::BIabs:
3633     return Builtin::BIlabs;
3634   case Builtin::BIlabs:
3635     return Builtin::BIllabs;
3636   case Builtin::BIllabs:
3637     return 0;
3638 
3639   case Builtin::BIfabsf:
3640     return Builtin::BIfabs;
3641   case Builtin::BIfabs:
3642     return Builtin::BIfabsl;
3643   case Builtin::BIfabsl:
3644     return 0;
3645 
3646   case Builtin::BIcabsf:
3647    return Builtin::BIcabs;
3648   case Builtin::BIcabs:
3649     return Builtin::BIcabsl;
3650   case Builtin::BIcabsl:
3651     return 0;
3652   }
3653 }
3654 
3655 // Returns the argument type of the absolute value function.
3656 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3657                                              unsigned AbsType) {
3658   if (AbsType == 0)
3659     return QualType();
3660 
3661   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3662   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3663   if (Error != ASTContext::GE_None)
3664     return QualType();
3665 
3666   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3667   if (!FT)
3668     return QualType();
3669 
3670   if (FT->getNumParams() != 1)
3671     return QualType();
3672 
3673   return FT->getParamType(0);
3674 }
3675 
3676 // Returns the best absolute value function, or zero, based on type and
3677 // current absolute value function.
3678 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3679                                    unsigned AbsFunctionKind) {
3680   unsigned BestKind = 0;
3681   uint64_t ArgSize = Context.getTypeSize(ArgType);
3682   for (unsigned Kind = AbsFunctionKind; Kind != 0;
3683        Kind = getLargerAbsoluteValueFunction(Kind)) {
3684     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3685     if (Context.getTypeSize(ParamType) >= ArgSize) {
3686       if (BestKind == 0)
3687         BestKind = Kind;
3688       else if (Context.hasSameType(ParamType, ArgType)) {
3689         BestKind = Kind;
3690         break;
3691       }
3692     }
3693   }
3694   return BestKind;
3695 }
3696 
3697 enum AbsoluteValueKind {
3698   AVK_Integer,
3699   AVK_Floating,
3700   AVK_Complex
3701 };
3702 
3703 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3704   if (T->isIntegralOrEnumerationType())
3705     return AVK_Integer;
3706   if (T->isRealFloatingType())
3707     return AVK_Floating;
3708   if (T->isAnyComplexType())
3709     return AVK_Complex;
3710 
3711   llvm_unreachable("Type not integer, floating, or complex");
3712 }
3713 
3714 // Changes the absolute value function to a different type.  Preserves whether
3715 // the function is a builtin.
3716 static unsigned changeAbsFunction(unsigned AbsKind,
3717                                   AbsoluteValueKind ValueKind) {
3718   switch (ValueKind) {
3719   case AVK_Integer:
3720     switch (AbsKind) {
3721     default:
3722       return 0;
3723     case Builtin::BI__builtin_fabsf:
3724     case Builtin::BI__builtin_fabs:
3725     case Builtin::BI__builtin_fabsl:
3726     case Builtin::BI__builtin_cabsf:
3727     case Builtin::BI__builtin_cabs:
3728     case Builtin::BI__builtin_cabsl:
3729       return Builtin::BI__builtin_abs;
3730     case Builtin::BIfabsf:
3731     case Builtin::BIfabs:
3732     case Builtin::BIfabsl:
3733     case Builtin::BIcabsf:
3734     case Builtin::BIcabs:
3735     case Builtin::BIcabsl:
3736       return Builtin::BIabs;
3737     }
3738   case AVK_Floating:
3739     switch (AbsKind) {
3740     default:
3741       return 0;
3742     case Builtin::BI__builtin_abs:
3743     case Builtin::BI__builtin_labs:
3744     case Builtin::BI__builtin_llabs:
3745     case Builtin::BI__builtin_cabsf:
3746     case Builtin::BI__builtin_cabs:
3747     case Builtin::BI__builtin_cabsl:
3748       return Builtin::BI__builtin_fabsf;
3749     case Builtin::BIabs:
3750     case Builtin::BIlabs:
3751     case Builtin::BIllabs:
3752     case Builtin::BIcabsf:
3753     case Builtin::BIcabs:
3754     case Builtin::BIcabsl:
3755       return Builtin::BIfabsf;
3756     }
3757   case AVK_Complex:
3758     switch (AbsKind) {
3759     default:
3760       return 0;
3761     case Builtin::BI__builtin_abs:
3762     case Builtin::BI__builtin_labs:
3763     case Builtin::BI__builtin_llabs:
3764     case Builtin::BI__builtin_fabsf:
3765     case Builtin::BI__builtin_fabs:
3766     case Builtin::BI__builtin_fabsl:
3767       return Builtin::BI__builtin_cabsf;
3768     case Builtin::BIabs:
3769     case Builtin::BIlabs:
3770     case Builtin::BIllabs:
3771     case Builtin::BIfabsf:
3772     case Builtin::BIfabs:
3773     case Builtin::BIfabsl:
3774       return Builtin::BIcabsf;
3775     }
3776   }
3777   llvm_unreachable("Unable to convert function");
3778 }
3779 
3780 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
3781   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3782   if (!FnInfo)
3783     return 0;
3784 
3785   switch (FDecl->getBuiltinID()) {
3786   default:
3787     return 0;
3788   case Builtin::BI__builtin_abs:
3789   case Builtin::BI__builtin_fabs:
3790   case Builtin::BI__builtin_fabsf:
3791   case Builtin::BI__builtin_fabsl:
3792   case Builtin::BI__builtin_labs:
3793   case Builtin::BI__builtin_llabs:
3794   case Builtin::BI__builtin_cabs:
3795   case Builtin::BI__builtin_cabsf:
3796   case Builtin::BI__builtin_cabsl:
3797   case Builtin::BIabs:
3798   case Builtin::BIlabs:
3799   case Builtin::BIllabs:
3800   case Builtin::BIfabs:
3801   case Builtin::BIfabsf:
3802   case Builtin::BIfabsl:
3803   case Builtin::BIcabs:
3804   case Builtin::BIcabsf:
3805   case Builtin::BIcabsl:
3806     return FDecl->getBuiltinID();
3807   }
3808   llvm_unreachable("Unknown Builtin type");
3809 }
3810 
3811 // If the replacement is valid, emit a note with replacement function.
3812 // Additionally, suggest including the proper header if not already included.
3813 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
3814                             unsigned AbsKind) {
3815   std::string AbsName = S.Context.BuiltinInfo.GetName(AbsKind);
3816 
3817   // Look up absolute value function in TU scope.
3818   DeclarationName DN(&S.Context.Idents.get(AbsName));
3819   LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3820   S.LookupName(R, S.TUScope);
3821 
3822   // Skip notes if multiple results found in lookup.
3823   if (!R.empty() && !R.isSingleResult())
3824     return;
3825 
3826   FunctionDecl *FD = 0;
3827   bool FoundFunction = R.isSingleResult();
3828   // When one result is found, see if it is the correct function.
3829   if (R.isSingleResult()) {
3830     FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3831     if (!FD || FD->getBuiltinID() != AbsKind)
3832       return;
3833   }
3834 
3835   // Look for local name conflict, prepend "::" as necessary.
3836   R.clear();
3837   S.LookupName(R, S.getCurScope());
3838 
3839   if (!FoundFunction) {
3840     if (!R.empty()) {
3841       AbsName = "::" + AbsName;
3842     }
3843   } else { // FoundFunction
3844     if (R.isSingleResult()) {
3845       if (R.getFoundDecl() != FD) {
3846         AbsName = "::" + AbsName;
3847       }
3848     } else if (!R.empty()) {
3849       AbsName = "::" + AbsName;
3850     }
3851   }
3852 
3853   S.Diag(Loc, diag::note_replace_abs_function)
3854       << AbsName << FixItHint::CreateReplacement(Range, AbsName);
3855 
3856   if (!FoundFunction) {
3857     S.Diag(Loc, diag::note_please_include_header)
3858         << S.Context.BuiltinInfo.getHeaderName(AbsKind)
3859         << S.Context.BuiltinInfo.GetName(AbsKind);
3860   }
3861 }
3862 
3863 // Warn when using the wrong abs() function.
3864 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3865                                       const FunctionDecl *FDecl,
3866                                       IdentifierInfo *FnInfo) {
3867   if (Call->getNumArgs() != 1)
3868     return;
3869 
3870   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
3871   if (AbsKind == 0)
3872     return;
3873 
3874   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3875   QualType ParamType = Call->getArg(0)->getType();
3876 
3877   // Unsigned types can not be negative.  Suggest to drop the absolute value
3878   // function.
3879   if (ArgType->isUnsignedIntegerType()) {
3880     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3881     Diag(Call->getExprLoc(), diag::note_remove_abs)
3882         << FDecl
3883         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3884     return;
3885   }
3886 
3887   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3888   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3889 
3890   // The argument and parameter are the same kind.  Check if they are the right
3891   // size.
3892   if (ArgValueKind == ParamValueKind) {
3893     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3894       return;
3895 
3896     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3897     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3898         << FDecl << ArgType << ParamType;
3899 
3900     if (NewAbsKind == 0)
3901       return;
3902 
3903     emitReplacement(*this, Call->getExprLoc(),
3904                     Call->getCallee()->getSourceRange(), NewAbsKind);
3905     return;
3906   }
3907 
3908   // ArgValueKind != ParamValueKind
3909   // The wrong type of absolute value function was used.  Attempt to find the
3910   // proper one.
3911   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3912   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3913   if (NewAbsKind == 0)
3914     return;
3915 
3916   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3917       << FDecl << ParamValueKind << ArgValueKind;
3918 
3919   emitReplacement(*this, Call->getExprLoc(),
3920                   Call->getCallee()->getSourceRange(), NewAbsKind);
3921   return;
3922 }
3923 
3924 //===--- CHECK: Standard memory functions ---------------------------------===//
3925 
3926 /// \brief Takes the expression passed to the size_t parameter of functions
3927 /// such as memcmp, strncat, etc and warns if it's a comparison.
3928 ///
3929 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3930 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3931                                            IdentifierInfo *FnName,
3932                                            SourceLocation FnLoc,
3933                                            SourceLocation RParenLoc) {
3934   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3935   if (!Size)
3936     return false;
3937 
3938   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3939   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3940     return false;
3941 
3942   Preprocessor &PP = S.getPreprocessor();
3943   SourceRange SizeRange = Size->getSourceRange();
3944   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3945       << SizeRange << FnName;
3946   S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note)
3947       << FnName
3948       << FixItHint::CreateInsertion(
3949              PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()),
3950              ")")
3951       << FixItHint::CreateRemoval(RParenLoc);
3952   S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note)
3953       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
3954       << FixItHint::CreateInsertion(
3955              PP.getLocForEndOfToken(SizeRange.getEnd()), ")");
3956 
3957   return true;
3958 }
3959 
3960 /// \brief Determine whether the given type is a dynamic class type (e.g.,
3961 /// whether it has a vtable).
3962 static bool isDynamicClassType(QualType T) {
3963   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3964     if (CXXRecordDecl *Definition = Record->getDefinition())
3965       if (Definition->isDynamicClass())
3966         return true;
3967 
3968   return false;
3969 }
3970 
3971 /// \brief If E is a sizeof expression, returns its argument expression,
3972 /// otherwise returns NULL.
3973 static const Expr *getSizeOfExprArg(const Expr* E) {
3974   if (const UnaryExprOrTypeTraitExpr *SizeOf =
3975       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3976     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3977       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
3978 
3979   return 0;
3980 }
3981 
3982 /// \brief If E is a sizeof expression, returns its argument type.
3983 static QualType getSizeOfArgType(const Expr* E) {
3984   if (const UnaryExprOrTypeTraitExpr *SizeOf =
3985       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3986     if (SizeOf->getKind() == clang::UETT_SizeOf)
3987       return SizeOf->getTypeOfArgument();
3988 
3989   return QualType();
3990 }
3991 
3992 /// \brief Check for dangerous or invalid arguments to memset().
3993 ///
3994 /// This issues warnings on known problematic, dangerous or unspecified
3995 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3996 /// function calls.
3997 ///
3998 /// \param Call The call expression to diagnose.
3999 void Sema::CheckMemaccessArguments(const CallExpr *Call,
4000                                    unsigned BId,
4001                                    IdentifierInfo *FnName) {
4002   assert(BId != 0);
4003 
4004   // It is possible to have a non-standard definition of memset.  Validate
4005   // we have enough arguments, and if not, abort further checking.
4006   unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
4007   if (Call->getNumArgs() < ExpectedNumArgs)
4008     return;
4009 
4010   unsigned LastArg = (BId == Builtin::BImemset ||
4011                       BId == Builtin::BIstrndup ? 1 : 2);
4012   unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
4013   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
4014 
4015   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4016                                      Call->getLocStart(), Call->getRParenLoc()))
4017     return;
4018 
4019   // We have special checking when the length is a sizeof expression.
4020   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4021   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4022   llvm::FoldingSetNodeID SizeOfArgID;
4023 
4024   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4025     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
4026     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
4027 
4028     QualType DestTy = Dest->getType();
4029     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4030       QualType PointeeTy = DestPtrTy->getPointeeType();
4031 
4032       // Never warn about void type pointers. This can be used to suppress
4033       // false positives.
4034       if (PointeeTy->isVoidType())
4035         continue;
4036 
4037       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4038       // actually comparing the expressions for equality. Because computing the
4039       // expression IDs can be expensive, we only do this if the diagnostic is
4040       // enabled.
4041       if (SizeOfArg &&
4042           Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
4043                                    SizeOfArg->getExprLoc())) {
4044         // We only compute IDs for expressions if the warning is enabled, and
4045         // cache the sizeof arg's ID.
4046         if (SizeOfArgID == llvm::FoldingSetNodeID())
4047           SizeOfArg->Profile(SizeOfArgID, Context, true);
4048         llvm::FoldingSetNodeID DestID;
4049         Dest->Profile(DestID, Context, true);
4050         if (DestID == SizeOfArgID) {
4051           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4052           //       over sizeof(src) as well.
4053           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
4054           StringRef ReadableName = FnName->getName();
4055 
4056           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
4057             if (UnaryOp->getOpcode() == UO_AddrOf)
4058               ActionIdx = 1; // If its an address-of operator, just remove it.
4059           if (!PointeeTy->isIncompleteType() &&
4060               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
4061             ActionIdx = 2; // If the pointee's size is sizeof(char),
4062                            // suggest an explicit length.
4063 
4064           // If the function is defined as a builtin macro, do not show macro
4065           // expansion.
4066           SourceLocation SL = SizeOfArg->getExprLoc();
4067           SourceRange DSR = Dest->getSourceRange();
4068           SourceRange SSR = SizeOfArg->getSourceRange();
4069           SourceManager &SM  = PP.getSourceManager();
4070 
4071           if (SM.isMacroArgExpansion(SL)) {
4072             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4073             SL = SM.getSpellingLoc(SL);
4074             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4075                              SM.getSpellingLoc(DSR.getEnd()));
4076             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4077                              SM.getSpellingLoc(SSR.getEnd()));
4078           }
4079 
4080           DiagRuntimeBehavior(SL, SizeOfArg,
4081                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
4082                                 << ReadableName
4083                                 << PointeeTy
4084                                 << DestTy
4085                                 << DSR
4086                                 << SSR);
4087           DiagRuntimeBehavior(SL, SizeOfArg,
4088                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4089                                 << ActionIdx
4090                                 << SSR);
4091 
4092           break;
4093         }
4094       }
4095 
4096       // Also check for cases where the sizeof argument is the exact same
4097       // type as the memory argument, and where it points to a user-defined
4098       // record type.
4099       if (SizeOfArgTy != QualType()) {
4100         if (PointeeTy->isRecordType() &&
4101             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4102           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4103                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
4104                                 << FnName << SizeOfArgTy << ArgIdx
4105                                 << PointeeTy << Dest->getSourceRange()
4106                                 << LenExpr->getSourceRange());
4107           break;
4108         }
4109       }
4110 
4111       // Always complain about dynamic classes.
4112       if (isDynamicClassType(PointeeTy)) {
4113 
4114         unsigned OperationType = 0;
4115         // "overwritten" if we're warning about the destination for any call
4116         // but memcmp; otherwise a verb appropriate to the call.
4117         if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4118           if (BId == Builtin::BImemcpy)
4119             OperationType = 1;
4120           else if(BId == Builtin::BImemmove)
4121             OperationType = 2;
4122           else if (BId == Builtin::BImemcmp)
4123             OperationType = 3;
4124         }
4125 
4126         DiagRuntimeBehavior(
4127           Dest->getExprLoc(), Dest,
4128           PDiag(diag::warn_dyn_class_memaccess)
4129             << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
4130             << FnName << PointeeTy
4131             << OperationType
4132             << Call->getCallee()->getSourceRange());
4133       } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4134                BId != Builtin::BImemset)
4135         DiagRuntimeBehavior(
4136           Dest->getExprLoc(), Dest,
4137           PDiag(diag::warn_arc_object_memaccess)
4138             << ArgIdx << FnName << PointeeTy
4139             << Call->getCallee()->getSourceRange());
4140       else
4141         continue;
4142 
4143       DiagRuntimeBehavior(
4144         Dest->getExprLoc(), Dest,
4145         PDiag(diag::note_bad_memaccess_silence)
4146           << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4147       break;
4148     }
4149   }
4150 }
4151 
4152 // A little helper routine: ignore addition and subtraction of integer literals.
4153 // This intentionally does not ignore all integer constant expressions because
4154 // we don't want to remove sizeof().
4155 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4156   Ex = Ex->IgnoreParenCasts();
4157 
4158   for (;;) {
4159     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4160     if (!BO || !BO->isAdditiveOp())
4161       break;
4162 
4163     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4164     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4165 
4166     if (isa<IntegerLiteral>(RHS))
4167       Ex = LHS;
4168     else if (isa<IntegerLiteral>(LHS))
4169       Ex = RHS;
4170     else
4171       break;
4172   }
4173 
4174   return Ex;
4175 }
4176 
4177 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4178                                                       ASTContext &Context) {
4179   // Only handle constant-sized or VLAs, but not flexible members.
4180   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4181     // Only issue the FIXIT for arrays of size > 1.
4182     if (CAT->getSize().getSExtValue() <= 1)
4183       return false;
4184   } else if (!Ty->isVariableArrayType()) {
4185     return false;
4186   }
4187   return true;
4188 }
4189 
4190 // Warn if the user has made the 'size' argument to strlcpy or strlcat
4191 // be the size of the source, instead of the destination.
4192 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4193                                     IdentifierInfo *FnName) {
4194 
4195   // Don't crash if the user has the wrong number of arguments
4196   if (Call->getNumArgs() != 3)
4197     return;
4198 
4199   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4200   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
4201   const Expr *CompareWithSrc = NULL;
4202 
4203   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4204                                      Call->getLocStart(), Call->getRParenLoc()))
4205     return;
4206 
4207   // Look for 'strlcpy(dst, x, sizeof(x))'
4208   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4209     CompareWithSrc = Ex;
4210   else {
4211     // Look for 'strlcpy(dst, x, strlen(x))'
4212     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
4213       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4214           SizeCall->getNumArgs() == 1)
4215         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4216     }
4217   }
4218 
4219   if (!CompareWithSrc)
4220     return;
4221 
4222   // Determine if the argument to sizeof/strlen is equal to the source
4223   // argument.  In principle there's all kinds of things you could do
4224   // here, for instance creating an == expression and evaluating it with
4225   // EvaluateAsBooleanCondition, but this uses a more direct technique:
4226   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4227   if (!SrcArgDRE)
4228     return;
4229 
4230   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4231   if (!CompareWithSrcDRE ||
4232       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4233     return;
4234 
4235   const Expr *OriginalSizeArg = Call->getArg(2);
4236   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4237     << OriginalSizeArg->getSourceRange() << FnName;
4238 
4239   // Output a FIXIT hint if the destination is an array (rather than a
4240   // pointer to an array).  This could be enhanced to handle some
4241   // pointers if we know the actual size, like if DstArg is 'array+2'
4242   // we could say 'sizeof(array)-2'.
4243   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
4244   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
4245     return;
4246 
4247   SmallString<128> sizeString;
4248   llvm::raw_svector_ostream OS(sizeString);
4249   OS << "sizeof(";
4250   DstArg->printPretty(OS, 0, getPrintingPolicy());
4251   OS << ")";
4252 
4253   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4254     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4255                                     OS.str());
4256 }
4257 
4258 /// Check if two expressions refer to the same declaration.
4259 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4260   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4261     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4262       return D1->getDecl() == D2->getDecl();
4263   return false;
4264 }
4265 
4266 static const Expr *getStrlenExprArg(const Expr *E) {
4267   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4268     const FunctionDecl *FD = CE->getDirectCallee();
4269     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
4270       return 0;
4271     return CE->getArg(0)->IgnoreParenCasts();
4272   }
4273   return 0;
4274 }
4275 
4276 // Warn on anti-patterns as the 'size' argument to strncat.
4277 // The correct size argument should look like following:
4278 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4279 void Sema::CheckStrncatArguments(const CallExpr *CE,
4280                                  IdentifierInfo *FnName) {
4281   // Don't crash if the user has the wrong number of arguments.
4282   if (CE->getNumArgs() < 3)
4283     return;
4284   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4285   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4286   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4287 
4288   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4289                                      CE->getRParenLoc()))
4290     return;
4291 
4292   // Identify common expressions, which are wrongly used as the size argument
4293   // to strncat and may lead to buffer overflows.
4294   unsigned PatternType = 0;
4295   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4296     // - sizeof(dst)
4297     if (referToTheSameDecl(SizeOfArg, DstArg))
4298       PatternType = 1;
4299     // - sizeof(src)
4300     else if (referToTheSameDecl(SizeOfArg, SrcArg))
4301       PatternType = 2;
4302   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4303     if (BE->getOpcode() == BO_Sub) {
4304       const Expr *L = BE->getLHS()->IgnoreParenCasts();
4305       const Expr *R = BE->getRHS()->IgnoreParenCasts();
4306       // - sizeof(dst) - strlen(dst)
4307       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4308           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4309         PatternType = 1;
4310       // - sizeof(src) - (anything)
4311       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4312         PatternType = 2;
4313     }
4314   }
4315 
4316   if (PatternType == 0)
4317     return;
4318 
4319   // Generate the diagnostic.
4320   SourceLocation SL = LenArg->getLocStart();
4321   SourceRange SR = LenArg->getSourceRange();
4322   SourceManager &SM  = PP.getSourceManager();
4323 
4324   // If the function is defined as a builtin macro, do not show macro expansion.
4325   if (SM.isMacroArgExpansion(SL)) {
4326     SL = SM.getSpellingLoc(SL);
4327     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4328                      SM.getSpellingLoc(SR.getEnd()));
4329   }
4330 
4331   // Check if the destination is an array (rather than a pointer to an array).
4332   QualType DstTy = DstArg->getType();
4333   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4334                                                                     Context);
4335   if (!isKnownSizeArray) {
4336     if (PatternType == 1)
4337       Diag(SL, diag::warn_strncat_wrong_size) << SR;
4338     else
4339       Diag(SL, diag::warn_strncat_src_size) << SR;
4340     return;
4341   }
4342 
4343   if (PatternType == 1)
4344     Diag(SL, diag::warn_strncat_large_size) << SR;
4345   else
4346     Diag(SL, diag::warn_strncat_src_size) << SR;
4347 
4348   SmallString<128> sizeString;
4349   llvm::raw_svector_ostream OS(sizeString);
4350   OS << "sizeof(";
4351   DstArg->printPretty(OS, 0, getPrintingPolicy());
4352   OS << ") - ";
4353   OS << "strlen(";
4354   DstArg->printPretty(OS, 0, getPrintingPolicy());
4355   OS << ") - 1";
4356 
4357   Diag(SL, diag::note_strncat_wrong_size)
4358     << FixItHint::CreateReplacement(SR, OS.str());
4359 }
4360 
4361 //===--- CHECK: Return Address of Stack Variable --------------------------===//
4362 
4363 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4364                      Decl *ParentDecl);
4365 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4366                       Decl *ParentDecl);
4367 
4368 /// CheckReturnStackAddr - Check if a return statement returns the address
4369 ///   of a stack variable.
4370 static void
4371 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4372                      SourceLocation ReturnLoc) {
4373 
4374   Expr *stackE = 0;
4375   SmallVector<DeclRefExpr *, 8> refVars;
4376 
4377   // Perform checking for returned stack addresses, local blocks,
4378   // label addresses or references to temporaries.
4379   if (lhsType->isPointerType() ||
4380       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
4381     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
4382   } else if (lhsType->isReferenceType()) {
4383     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
4384   }
4385 
4386   if (stackE == 0)
4387     return; // Nothing suspicious was found.
4388 
4389   SourceLocation diagLoc;
4390   SourceRange diagRange;
4391   if (refVars.empty()) {
4392     diagLoc = stackE->getLocStart();
4393     diagRange = stackE->getSourceRange();
4394   } else {
4395     // We followed through a reference variable. 'stackE' contains the
4396     // problematic expression but we will warn at the return statement pointing
4397     // at the reference variable. We will later display the "trail" of
4398     // reference variables using notes.
4399     diagLoc = refVars[0]->getLocStart();
4400     diagRange = refVars[0]->getSourceRange();
4401   }
4402 
4403   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
4404     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
4405                                              : diag::warn_ret_stack_addr)
4406      << DR->getDecl()->getDeclName() << diagRange;
4407   } else if (isa<BlockExpr>(stackE)) { // local block.
4408     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
4409   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
4410     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
4411   } else { // local temporary.
4412     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4413                                                : diag::warn_ret_local_temp_addr)
4414      << diagRange;
4415   }
4416 
4417   // Display the "trail" of reference variables that we followed until we
4418   // found the problematic expression using notes.
4419   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4420     VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4421     // If this var binds to another reference var, show the range of the next
4422     // var, otherwise the var binds to the problematic expression, in which case
4423     // show the range of the expression.
4424     SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4425                                   : stackE->getSourceRange();
4426     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4427         << VD->getDeclName() << range;
4428   }
4429 }
4430 
4431 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4432 ///  check if the expression in a return statement evaluates to an address
4433 ///  to a location on the stack, a local block, an address of a label, or a
4434 ///  reference to local temporary. The recursion is used to traverse the
4435 ///  AST of the return expression, with recursion backtracking when we
4436 ///  encounter a subexpression that (1) clearly does not lead to one of the
4437 ///  above problematic expressions (2) is something we cannot determine leads to
4438 ///  a problematic expression based on such local checking.
4439 ///
4440 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
4441 ///  the expression that they point to. Such variables are added to the
4442 ///  'refVars' vector so that we know what the reference variable "trail" was.
4443 ///
4444 ///  EvalAddr processes expressions that are pointers that are used as
4445 ///  references (and not L-values).  EvalVal handles all other values.
4446 ///  At the base case of the recursion is a check for the above problematic
4447 ///  expressions.
4448 ///
4449 ///  This implementation handles:
4450 ///
4451 ///   * pointer-to-pointer casts
4452 ///   * implicit conversions from array references to pointers
4453 ///   * taking the address of fields
4454 ///   * arbitrary interplay between "&" and "*" operators
4455 ///   * pointer arithmetic from an address of a stack variable
4456 ///   * taking the address of an array element where the array is on the stack
4457 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4458                       Decl *ParentDecl) {
4459   if (E->isTypeDependent())
4460     return NULL;
4461 
4462   // We should only be called for evaluating pointer expressions.
4463   assert((E->getType()->isAnyPointerType() ||
4464           E->getType()->isBlockPointerType() ||
4465           E->getType()->isObjCQualifiedIdType()) &&
4466          "EvalAddr only works on pointers");
4467 
4468   E = E->IgnoreParens();
4469 
4470   // Our "symbolic interpreter" is just a dispatch off the currently
4471   // viewed AST node.  We then recursively traverse the AST by calling
4472   // EvalAddr and EvalVal appropriately.
4473   switch (E->getStmtClass()) {
4474   case Stmt::DeclRefExprClass: {
4475     DeclRefExpr *DR = cast<DeclRefExpr>(E);
4476 
4477     // If we leave the immediate function, the lifetime isn't about to end.
4478     if (DR->refersToEnclosingLocal())
4479       return 0;
4480 
4481     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4482       // If this is a reference variable, follow through to the expression that
4483       // it points to.
4484       if (V->hasLocalStorage() &&
4485           V->getType()->isReferenceType() && V->hasInit()) {
4486         // Add the reference variable to the "trail".
4487         refVars.push_back(DR);
4488         return EvalAddr(V->getInit(), refVars, ParentDecl);
4489       }
4490 
4491     return NULL;
4492   }
4493 
4494   case Stmt::UnaryOperatorClass: {
4495     // The only unary operator that make sense to handle here
4496     // is AddrOf.  All others don't make sense as pointers.
4497     UnaryOperator *U = cast<UnaryOperator>(E);
4498 
4499     if (U->getOpcode() == UO_AddrOf)
4500       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
4501     else
4502       return NULL;
4503   }
4504 
4505   case Stmt::BinaryOperatorClass: {
4506     // Handle pointer arithmetic.  All other binary operators are not valid
4507     // in this context.
4508     BinaryOperator *B = cast<BinaryOperator>(E);
4509     BinaryOperatorKind op = B->getOpcode();
4510 
4511     if (op != BO_Add && op != BO_Sub)
4512       return NULL;
4513 
4514     Expr *Base = B->getLHS();
4515 
4516     // Determine which argument is the real pointer base.  It could be
4517     // the RHS argument instead of the LHS.
4518     if (!Base->getType()->isPointerType()) Base = B->getRHS();
4519 
4520     assert (Base->getType()->isPointerType());
4521     return EvalAddr(Base, refVars, ParentDecl);
4522   }
4523 
4524   // For conditional operators we need to see if either the LHS or RHS are
4525   // valid DeclRefExpr*s.  If one of them is valid, we return it.
4526   case Stmt::ConditionalOperatorClass: {
4527     ConditionalOperator *C = cast<ConditionalOperator>(E);
4528 
4529     // Handle the GNU extension for missing LHS.
4530     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4531     if (Expr *LHSExpr = C->getLHS()) {
4532       // In C++, we can have a throw-expression, which has 'void' type.
4533       if (!LHSExpr->getType()->isVoidType())
4534         if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
4535           return LHS;
4536     }
4537 
4538     // In C++, we can have a throw-expression, which has 'void' type.
4539     if (C->getRHS()->getType()->isVoidType())
4540       return 0;
4541 
4542     return EvalAddr(C->getRHS(), refVars, ParentDecl);
4543   }
4544 
4545   case Stmt::BlockExprClass:
4546     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
4547       return E; // local block.
4548     return NULL;
4549 
4550   case Stmt::AddrLabelExprClass:
4551     return E; // address of label.
4552 
4553   case Stmt::ExprWithCleanupsClass:
4554     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4555                     ParentDecl);
4556 
4557   // For casts, we need to handle conversions from arrays to
4558   // pointer values, and pointer-to-pointer conversions.
4559   case Stmt::ImplicitCastExprClass:
4560   case Stmt::CStyleCastExprClass:
4561   case Stmt::CXXFunctionalCastExprClass:
4562   case Stmt::ObjCBridgedCastExprClass:
4563   case Stmt::CXXStaticCastExprClass:
4564   case Stmt::CXXDynamicCastExprClass:
4565   case Stmt::CXXConstCastExprClass:
4566   case Stmt::CXXReinterpretCastExprClass: {
4567     Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4568     switch (cast<CastExpr>(E)->getCastKind()) {
4569     case CK_BitCast:
4570     case CK_LValueToRValue:
4571     case CK_NoOp:
4572     case CK_BaseToDerived:
4573     case CK_DerivedToBase:
4574     case CK_UncheckedDerivedToBase:
4575     case CK_Dynamic:
4576     case CK_CPointerToObjCPointerCast:
4577     case CK_BlockPointerToObjCPointerCast:
4578     case CK_AnyPointerToBlockPointerCast:
4579       return EvalAddr(SubExpr, refVars, ParentDecl);
4580 
4581     case CK_ArrayToPointerDecay:
4582       return EvalVal(SubExpr, refVars, ParentDecl);
4583 
4584     default:
4585       return 0;
4586     }
4587   }
4588 
4589   case Stmt::MaterializeTemporaryExprClass:
4590     if (Expr *Result = EvalAddr(
4591                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4592                                 refVars, ParentDecl))
4593       return Result;
4594 
4595     return E;
4596 
4597   // Everything else: we simply don't reason about them.
4598   default:
4599     return NULL;
4600   }
4601 }
4602 
4603 
4604 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
4605 ///   See the comments for EvalAddr for more details.
4606 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4607                      Decl *ParentDecl) {
4608 do {
4609   // We should only be called for evaluating non-pointer expressions, or
4610   // expressions with a pointer type that are not used as references but instead
4611   // are l-values (e.g., DeclRefExpr with a pointer type).
4612 
4613   // Our "symbolic interpreter" is just a dispatch off the currently
4614   // viewed AST node.  We then recursively traverse the AST by calling
4615   // EvalAddr and EvalVal appropriately.
4616 
4617   E = E->IgnoreParens();
4618   switch (E->getStmtClass()) {
4619   case Stmt::ImplicitCastExprClass: {
4620     ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
4621     if (IE->getValueKind() == VK_LValue) {
4622       E = IE->getSubExpr();
4623       continue;
4624     }
4625     return NULL;
4626   }
4627 
4628   case Stmt::ExprWithCleanupsClass:
4629     return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
4630 
4631   case Stmt::DeclRefExprClass: {
4632     // When we hit a DeclRefExpr we are looking at code that refers to a
4633     // variable's name. If it's not a reference variable we check if it has
4634     // local storage within the function, and if so, return the expression.
4635     DeclRefExpr *DR = cast<DeclRefExpr>(E);
4636 
4637     // If we leave the immediate function, the lifetime isn't about to end.
4638     if (DR->refersToEnclosingLocal())
4639       return 0;
4640 
4641     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4642       // Check if it refers to itself, e.g. "int& i = i;".
4643       if (V == ParentDecl)
4644         return DR;
4645 
4646       if (V->hasLocalStorage()) {
4647         if (!V->getType()->isReferenceType())
4648           return DR;
4649 
4650         // Reference variable, follow through to the expression that
4651         // it points to.
4652         if (V->hasInit()) {
4653           // Add the reference variable to the "trail".
4654           refVars.push_back(DR);
4655           return EvalVal(V->getInit(), refVars, V);
4656         }
4657       }
4658     }
4659 
4660     return NULL;
4661   }
4662 
4663   case Stmt::UnaryOperatorClass: {
4664     // The only unary operator that make sense to handle here
4665     // is Deref.  All others don't resolve to a "name."  This includes
4666     // handling all sorts of rvalues passed to a unary operator.
4667     UnaryOperator *U = cast<UnaryOperator>(E);
4668 
4669     if (U->getOpcode() == UO_Deref)
4670       return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
4671 
4672     return NULL;
4673   }
4674 
4675   case Stmt::ArraySubscriptExprClass: {
4676     // Array subscripts are potential references to data on the stack.  We
4677     // retrieve the DeclRefExpr* for the array variable if it indeed
4678     // has local storage.
4679     return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
4680   }
4681 
4682   case Stmt::ConditionalOperatorClass: {
4683     // For conditional operators we need to see if either the LHS or RHS are
4684     // non-NULL Expr's.  If one is non-NULL, we return it.
4685     ConditionalOperator *C = cast<ConditionalOperator>(E);
4686 
4687     // Handle the GNU extension for missing LHS.
4688     if (Expr *LHSExpr = C->getLHS()) {
4689       // In C++, we can have a throw-expression, which has 'void' type.
4690       if (!LHSExpr->getType()->isVoidType())
4691         if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4692           return LHS;
4693     }
4694 
4695     // In C++, we can have a throw-expression, which has 'void' type.
4696     if (C->getRHS()->getType()->isVoidType())
4697       return 0;
4698 
4699     return EvalVal(C->getRHS(), refVars, ParentDecl);
4700   }
4701 
4702   // Accesses to members are potential references to data on the stack.
4703   case Stmt::MemberExprClass: {
4704     MemberExpr *M = cast<MemberExpr>(E);
4705 
4706     // Check for indirect access.  We only want direct field accesses.
4707     if (M->isArrow())
4708       return NULL;
4709 
4710     // Check whether the member type is itself a reference, in which case
4711     // we're not going to refer to the member, but to what the member refers to.
4712     if (M->getMemberDecl()->getType()->isReferenceType())
4713       return NULL;
4714 
4715     return EvalVal(M->getBase(), refVars, ParentDecl);
4716   }
4717 
4718   case Stmt::MaterializeTemporaryExprClass:
4719     if (Expr *Result = EvalVal(
4720                           cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4721                                refVars, ParentDecl))
4722       return Result;
4723 
4724     return E;
4725 
4726   default:
4727     // Check that we don't return or take the address of a reference to a
4728     // temporary. This is only useful in C++.
4729     if (!E->isTypeDependent() && E->isRValue())
4730       return E;
4731 
4732     // Everything else: we simply don't reason about them.
4733     return NULL;
4734   }
4735 } while (true);
4736 }
4737 
4738 void
4739 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4740                          SourceLocation ReturnLoc,
4741                          bool isObjCMethod,
4742                          const AttrVec *Attrs,
4743                          const FunctionDecl *FD) {
4744   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4745 
4746   // Check if the return value is null but should not be.
4747   if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4748       CheckNonNullExpr(*this, RetValExp))
4749     Diag(ReturnLoc, diag::warn_null_ret)
4750       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
4751 
4752   // C++11 [basic.stc.dynamic.allocation]p4:
4753   //   If an allocation function declared with a non-throwing
4754   //   exception-specification fails to allocate storage, it shall return
4755   //   a null pointer. Any other allocation function that fails to allocate
4756   //   storage shall indicate failure only by throwing an exception [...]
4757   if (FD) {
4758     OverloadedOperatorKind Op = FD->getOverloadedOperator();
4759     if (Op == OO_New || Op == OO_Array_New) {
4760       const FunctionProtoType *Proto
4761         = FD->getType()->castAs<FunctionProtoType>();
4762       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4763           CheckNonNullExpr(*this, RetValExp))
4764         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4765           << FD << getLangOpts().CPlusPlus11;
4766     }
4767   }
4768 }
4769 
4770 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4771 
4772 /// Check for comparisons of floating point operands using != and ==.
4773 /// Issue a warning if these are no self-comparisons, as they are not likely
4774 /// to do what the programmer intended.
4775 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
4776   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4777   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
4778 
4779   // Special case: check for x == x (which is OK).
4780   // Do not emit warnings for such cases.
4781   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4782     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4783       if (DRL->getDecl() == DRR->getDecl())
4784         return;
4785 
4786 
4787   // Special case: check for comparisons against literals that can be exactly
4788   //  represented by APFloat.  In such cases, do not emit a warning.  This
4789   //  is a heuristic: often comparison against such literals are used to
4790   //  detect if a value in a variable has not changed.  This clearly can
4791   //  lead to false negatives.
4792   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4793     if (FLL->isExact())
4794       return;
4795   } else
4796     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4797       if (FLR->isExact())
4798         return;
4799 
4800   // Check for comparisons with builtin types.
4801   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4802     if (CL->getBuiltinCallee())
4803       return;
4804 
4805   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4806     if (CR->getBuiltinCallee())
4807       return;
4808 
4809   // Emit the diagnostic.
4810   Diag(Loc, diag::warn_floatingpoint_eq)
4811     << LHS->getSourceRange() << RHS->getSourceRange();
4812 }
4813 
4814 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4815 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
4816 
4817 namespace {
4818 
4819 /// Structure recording the 'active' range of an integer-valued
4820 /// expression.
4821 struct IntRange {
4822   /// The number of bits active in the int.
4823   unsigned Width;
4824 
4825   /// True if the int is known not to have negative values.
4826   bool NonNegative;
4827 
4828   IntRange(unsigned Width, bool NonNegative)
4829     : Width(Width), NonNegative(NonNegative)
4830   {}
4831 
4832   /// Returns the range of the bool type.
4833   static IntRange forBoolType() {
4834     return IntRange(1, true);
4835   }
4836 
4837   /// Returns the range of an opaque value of the given integral type.
4838   static IntRange forValueOfType(ASTContext &C, QualType T) {
4839     return forValueOfCanonicalType(C,
4840                           T->getCanonicalTypeInternal().getTypePtr());
4841   }
4842 
4843   /// Returns the range of an opaque value of a canonical integral type.
4844   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
4845     assert(T->isCanonicalUnqualified());
4846 
4847     if (const VectorType *VT = dyn_cast<VectorType>(T))
4848       T = VT->getElementType().getTypePtr();
4849     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4850       T = CT->getElementType().getTypePtr();
4851 
4852     // For enum types, use the known bit width of the enumerators.
4853     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
4854       EnumDecl *Enum = ET->getDecl();
4855       if (!Enum->isCompleteDefinition())
4856         return IntRange(C.getIntWidth(QualType(T, 0)), false);
4857 
4858       unsigned NumPositive = Enum->getNumPositiveBits();
4859       unsigned NumNegative = Enum->getNumNegativeBits();
4860 
4861       if (NumNegative == 0)
4862         return IntRange(NumPositive, true/*NonNegative*/);
4863       else
4864         return IntRange(std::max(NumPositive + 1, NumNegative),
4865                         false/*NonNegative*/);
4866     }
4867 
4868     const BuiltinType *BT = cast<BuiltinType>(T);
4869     assert(BT->isInteger());
4870 
4871     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4872   }
4873 
4874   /// Returns the "target" range of a canonical integral type, i.e.
4875   /// the range of values expressible in the type.
4876   ///
4877   /// This matches forValueOfCanonicalType except that enums have the
4878   /// full range of their type, not the range of their enumerators.
4879   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4880     assert(T->isCanonicalUnqualified());
4881 
4882     if (const VectorType *VT = dyn_cast<VectorType>(T))
4883       T = VT->getElementType().getTypePtr();
4884     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4885       T = CT->getElementType().getTypePtr();
4886     if (const EnumType *ET = dyn_cast<EnumType>(T))
4887       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
4888 
4889     const BuiltinType *BT = cast<BuiltinType>(T);
4890     assert(BT->isInteger());
4891 
4892     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4893   }
4894 
4895   /// Returns the supremum of two ranges: i.e. their conservative merge.
4896   static IntRange join(IntRange L, IntRange R) {
4897     return IntRange(std::max(L.Width, R.Width),
4898                     L.NonNegative && R.NonNegative);
4899   }
4900 
4901   /// Returns the infinum of two ranges: i.e. their aggressive merge.
4902   static IntRange meet(IntRange L, IntRange R) {
4903     return IntRange(std::min(L.Width, R.Width),
4904                     L.NonNegative || R.NonNegative);
4905   }
4906 };
4907 
4908 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4909                               unsigned MaxWidth) {
4910   if (value.isSigned() && value.isNegative())
4911     return IntRange(value.getMinSignedBits(), false);
4912 
4913   if (value.getBitWidth() > MaxWidth)
4914     value = value.trunc(MaxWidth);
4915 
4916   // isNonNegative() just checks the sign bit without considering
4917   // signedness.
4918   return IntRange(value.getActiveBits(), true);
4919 }
4920 
4921 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4922                               unsigned MaxWidth) {
4923   if (result.isInt())
4924     return GetValueRange(C, result.getInt(), MaxWidth);
4925 
4926   if (result.isVector()) {
4927     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4928     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4929       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4930       R = IntRange::join(R, El);
4931     }
4932     return R;
4933   }
4934 
4935   if (result.isComplexInt()) {
4936     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4937     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4938     return IntRange::join(R, I);
4939   }
4940 
4941   // This can happen with lossless casts to intptr_t of "based" lvalues.
4942   // Assume it might use arbitrary bits.
4943   // FIXME: The only reason we need to pass the type in here is to get
4944   // the sign right on this one case.  It would be nice if APValue
4945   // preserved this.
4946   assert(result.isLValue() || result.isAddrLabelDiff());
4947   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
4948 }
4949 
4950 static QualType GetExprType(Expr *E) {
4951   QualType Ty = E->getType();
4952   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4953     Ty = AtomicRHS->getValueType();
4954   return Ty;
4955 }
4956 
4957 /// Pseudo-evaluate the given integer expression, estimating the
4958 /// range of values it might take.
4959 ///
4960 /// \param MaxWidth - the width to which the value will be truncated
4961 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
4962   E = E->IgnoreParens();
4963 
4964   // Try a full evaluation first.
4965   Expr::EvalResult result;
4966   if (E->EvaluateAsRValue(result, C))
4967     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
4968 
4969   // I think we only want to look through implicit casts here; if the
4970   // user has an explicit widening cast, we should treat the value as
4971   // being of the new, wider type.
4972   if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
4973     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
4974       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4975 
4976     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
4977 
4978     bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
4979 
4980     // Assume that non-integer casts can span the full range of the type.
4981     if (!isIntegerCast)
4982       return OutputTypeRange;
4983 
4984     IntRange SubRange
4985       = GetExprRange(C, CE->getSubExpr(),
4986                      std::min(MaxWidth, OutputTypeRange.Width));
4987 
4988     // Bail out if the subexpr's range is as wide as the cast type.
4989     if (SubRange.Width >= OutputTypeRange.Width)
4990       return OutputTypeRange;
4991 
4992     // Otherwise, we take the smaller width, and we're non-negative if
4993     // either the output type or the subexpr is.
4994     return IntRange(SubRange.Width,
4995                     SubRange.NonNegative || OutputTypeRange.NonNegative);
4996   }
4997 
4998   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4999     // If we can fold the condition, just take that operand.
5000     bool CondResult;
5001     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5002       return GetExprRange(C, CondResult ? CO->getTrueExpr()
5003                                         : CO->getFalseExpr(),
5004                           MaxWidth);
5005 
5006     // Otherwise, conservatively merge.
5007     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5008     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5009     return IntRange::join(L, R);
5010   }
5011 
5012   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5013     switch (BO->getOpcode()) {
5014 
5015     // Boolean-valued operations are single-bit and positive.
5016     case BO_LAnd:
5017     case BO_LOr:
5018     case BO_LT:
5019     case BO_GT:
5020     case BO_LE:
5021     case BO_GE:
5022     case BO_EQ:
5023     case BO_NE:
5024       return IntRange::forBoolType();
5025 
5026     // The type of the assignments is the type of the LHS, so the RHS
5027     // is not necessarily the same type.
5028     case BO_MulAssign:
5029     case BO_DivAssign:
5030     case BO_RemAssign:
5031     case BO_AddAssign:
5032     case BO_SubAssign:
5033     case BO_XorAssign:
5034     case BO_OrAssign:
5035       // TODO: bitfields?
5036       return IntRange::forValueOfType(C, GetExprType(E));
5037 
5038     // Simple assignments just pass through the RHS, which will have
5039     // been coerced to the LHS type.
5040     case BO_Assign:
5041       // TODO: bitfields?
5042       return GetExprRange(C, BO->getRHS(), MaxWidth);
5043 
5044     // Operations with opaque sources are black-listed.
5045     case BO_PtrMemD:
5046     case BO_PtrMemI:
5047       return IntRange::forValueOfType(C, GetExprType(E));
5048 
5049     // Bitwise-and uses the *infinum* of the two source ranges.
5050     case BO_And:
5051     case BO_AndAssign:
5052       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5053                             GetExprRange(C, BO->getRHS(), MaxWidth));
5054 
5055     // Left shift gets black-listed based on a judgement call.
5056     case BO_Shl:
5057       // ...except that we want to treat '1 << (blah)' as logically
5058       // positive.  It's an important idiom.
5059       if (IntegerLiteral *I
5060             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5061         if (I->getValue() == 1) {
5062           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
5063           return IntRange(R.Width, /*NonNegative*/ true);
5064         }
5065       }
5066       // fallthrough
5067 
5068     case BO_ShlAssign:
5069       return IntRange::forValueOfType(C, GetExprType(E));
5070 
5071     // Right shift by a constant can narrow its left argument.
5072     case BO_Shr:
5073     case BO_ShrAssign: {
5074       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5075 
5076       // If the shift amount is a positive constant, drop the width by
5077       // that much.
5078       llvm::APSInt shift;
5079       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5080           shift.isNonNegative()) {
5081         unsigned zext = shift.getZExtValue();
5082         if (zext >= L.Width)
5083           L.Width = (L.NonNegative ? 0 : 1);
5084         else
5085           L.Width -= zext;
5086       }
5087 
5088       return L;
5089     }
5090 
5091     // Comma acts as its right operand.
5092     case BO_Comma:
5093       return GetExprRange(C, BO->getRHS(), MaxWidth);
5094 
5095     // Black-list pointer subtractions.
5096     case BO_Sub:
5097       if (BO->getLHS()->getType()->isPointerType())
5098         return IntRange::forValueOfType(C, GetExprType(E));
5099       break;
5100 
5101     // The width of a division result is mostly determined by the size
5102     // of the LHS.
5103     case BO_Div: {
5104       // Don't 'pre-truncate' the operands.
5105       unsigned opWidth = C.getIntWidth(GetExprType(E));
5106       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5107 
5108       // If the divisor is constant, use that.
5109       llvm::APSInt divisor;
5110       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5111         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5112         if (log2 >= L.Width)
5113           L.Width = (L.NonNegative ? 0 : 1);
5114         else
5115           L.Width = std::min(L.Width - log2, MaxWidth);
5116         return L;
5117       }
5118 
5119       // Otherwise, just use the LHS's width.
5120       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5121       return IntRange(L.Width, L.NonNegative && R.NonNegative);
5122     }
5123 
5124     // The result of a remainder can't be larger than the result of
5125     // either side.
5126     case BO_Rem: {
5127       // Don't 'pre-truncate' the operands.
5128       unsigned opWidth = C.getIntWidth(GetExprType(E));
5129       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5130       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5131 
5132       IntRange meet = IntRange::meet(L, R);
5133       meet.Width = std::min(meet.Width, MaxWidth);
5134       return meet;
5135     }
5136 
5137     // The default behavior is okay for these.
5138     case BO_Mul:
5139     case BO_Add:
5140     case BO_Xor:
5141     case BO_Or:
5142       break;
5143     }
5144 
5145     // The default case is to treat the operation as if it were closed
5146     // on the narrowest type that encompasses both operands.
5147     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5148     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5149     return IntRange::join(L, R);
5150   }
5151 
5152   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5153     switch (UO->getOpcode()) {
5154     // Boolean-valued operations are white-listed.
5155     case UO_LNot:
5156       return IntRange::forBoolType();
5157 
5158     // Operations with opaque sources are black-listed.
5159     case UO_Deref:
5160     case UO_AddrOf: // should be impossible
5161       return IntRange::forValueOfType(C, GetExprType(E));
5162 
5163     default:
5164       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5165     }
5166   }
5167 
5168   if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5169     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5170 
5171   if (FieldDecl *BitField = E->getSourceBitField())
5172     return IntRange(BitField->getBitWidthValue(C),
5173                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
5174 
5175   return IntRange::forValueOfType(C, GetExprType(E));
5176 }
5177 
5178 static IntRange GetExprRange(ASTContext &C, Expr *E) {
5179   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
5180 }
5181 
5182 /// Checks whether the given value, which currently has the given
5183 /// source semantics, has the same value when coerced through the
5184 /// target semantics.
5185 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5186                                  const llvm::fltSemantics &Src,
5187                                  const llvm::fltSemantics &Tgt) {
5188   llvm::APFloat truncated = value;
5189 
5190   bool ignored;
5191   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5192   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5193 
5194   return truncated.bitwiseIsEqual(value);
5195 }
5196 
5197 /// Checks whether the given value, which currently has the given
5198 /// source semantics, has the same value when coerced through the
5199 /// target semantics.
5200 ///
5201 /// The value might be a vector of floats (or a complex number).
5202 static bool IsSameFloatAfterCast(const APValue &value,
5203                                  const llvm::fltSemantics &Src,
5204                                  const llvm::fltSemantics &Tgt) {
5205   if (value.isFloat())
5206     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5207 
5208   if (value.isVector()) {
5209     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5210       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5211         return false;
5212     return true;
5213   }
5214 
5215   assert(value.isComplexFloat());
5216   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5217           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5218 }
5219 
5220 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
5221 
5222 static bool IsZero(Sema &S, Expr *E) {
5223   // Suppress cases where we are comparing against an enum constant.
5224   if (const DeclRefExpr *DR =
5225       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5226     if (isa<EnumConstantDecl>(DR->getDecl()))
5227       return false;
5228 
5229   // Suppress cases where the '0' value is expanded from a macro.
5230   if (E->getLocStart().isMacroID())
5231     return false;
5232 
5233   llvm::APSInt Value;
5234   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5235 }
5236 
5237 static bool HasEnumType(Expr *E) {
5238   // Strip off implicit integral promotions.
5239   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5240     if (ICE->getCastKind() != CK_IntegralCast &&
5241         ICE->getCastKind() != CK_NoOp)
5242       break;
5243     E = ICE->getSubExpr();
5244   }
5245 
5246   return E->getType()->isEnumeralType();
5247 }
5248 
5249 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
5250   // Disable warning in template instantiations.
5251   if (!S.ActiveTemplateInstantiations.empty())
5252     return;
5253 
5254   BinaryOperatorKind op = E->getOpcode();
5255   if (E->isValueDependent())
5256     return;
5257 
5258   if (op == BO_LT && IsZero(S, E->getRHS())) {
5259     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5260       << "< 0" << "false" << HasEnumType(E->getLHS())
5261       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5262   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
5263     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5264       << ">= 0" << "true" << HasEnumType(E->getLHS())
5265       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5266   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
5267     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5268       << "0 >" << "false" << HasEnumType(E->getRHS())
5269       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5270   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
5271     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5272       << "0 <=" << "true" << HasEnumType(E->getRHS())
5273       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5274   }
5275 }
5276 
5277 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
5278                                          Expr *Constant, Expr *Other,
5279                                          llvm::APSInt Value,
5280                                          bool RhsConstant) {
5281   // Disable warning in template instantiations.
5282   if (!S.ActiveTemplateInstantiations.empty())
5283     return;
5284 
5285   // 0 values are handled later by CheckTrivialUnsignedComparison().
5286   if (Value == 0)
5287     return;
5288 
5289   BinaryOperatorKind op = E->getOpcode();
5290   QualType OtherT = Other->getType();
5291   QualType ConstantT = Constant->getType();
5292   QualType CommonT = E->getLHS()->getType();
5293   if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5294     return;
5295   assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
5296          && "comparison with non-integer type");
5297 
5298   bool ConstantSigned = ConstantT->isSignedIntegerType();
5299   bool CommonSigned = CommonT->isSignedIntegerType();
5300 
5301   bool EqualityOnly = false;
5302 
5303   // TODO: Investigate using GetExprRange() to get tighter bounds on
5304   // on the bit ranges.
5305   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5306   unsigned OtherWidth = OtherRange.Width;
5307 
5308   if (CommonSigned) {
5309     // The common type is signed, therefore no signed to unsigned conversion.
5310     if (!OtherRange.NonNegative) {
5311       // Check that the constant is representable in type OtherT.
5312       if (ConstantSigned) {
5313         if (OtherWidth >= Value.getMinSignedBits())
5314           return;
5315       } else { // !ConstantSigned
5316         if (OtherWidth >= Value.getActiveBits() + 1)
5317           return;
5318       }
5319     } else { // !OtherSigned
5320       // Check that the constant is representable in type OtherT.
5321       // Negative values are out of range.
5322       if (ConstantSigned) {
5323         if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5324           return;
5325       } else { // !ConstantSigned
5326         if (OtherWidth >= Value.getActiveBits())
5327           return;
5328       }
5329     }
5330   } else {  // !CommonSigned
5331     if (OtherRange.NonNegative) {
5332       if (OtherWidth >= Value.getActiveBits())
5333         return;
5334     } else if (!OtherRange.NonNegative && !ConstantSigned) {
5335       // Check to see if the constant is representable in OtherT.
5336       if (OtherWidth > Value.getActiveBits())
5337         return;
5338       // Check to see if the constant is equivalent to a negative value
5339       // cast to CommonT.
5340       if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
5341           Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5342         return;
5343       // The constant value rests between values that OtherT can represent after
5344       // conversion.  Relational comparison still works, but equality
5345       // comparisons will be tautological.
5346       EqualityOnly = true;
5347     } else { // OtherSigned && ConstantSigned
5348       assert(0 && "Two signed types converted to unsigned types.");
5349     }
5350   }
5351 
5352   bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5353 
5354   bool IsTrue = true;
5355   if (op == BO_EQ || op == BO_NE) {
5356     IsTrue = op == BO_NE;
5357   } else if (EqualityOnly) {
5358     return;
5359   } else if (RhsConstant) {
5360     if (op == BO_GT || op == BO_GE)
5361       IsTrue = !PositiveConstant;
5362     else // op == BO_LT || op == BO_LE
5363       IsTrue = PositiveConstant;
5364   } else {
5365     if (op == BO_LT || op == BO_LE)
5366       IsTrue = !PositiveConstant;
5367     else // op == BO_GT || op == BO_GE
5368       IsTrue = PositiveConstant;
5369   }
5370 
5371   // If this is a comparison to an enum constant, include that
5372   // constant in the diagnostic.
5373   const EnumConstantDecl *ED = 0;
5374   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5375     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5376 
5377   SmallString<64> PrettySourceValue;
5378   llvm::raw_svector_ostream OS(PrettySourceValue);
5379   if (ED)
5380     OS << '\'' << *ED << "' (" << Value << ")";
5381   else
5382     OS << Value;
5383 
5384   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5385                         S.PDiag(diag::warn_out_of_range_compare)
5386                           << OS.str() << OtherT << IsTrue
5387                           << E->getLHS()->getSourceRange()
5388                           << E->getRHS()->getSourceRange());
5389 }
5390 
5391 /// Analyze the operands of the given comparison.  Implements the
5392 /// fallback case from AnalyzeComparison.
5393 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
5394   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5395   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5396 }
5397 
5398 /// \brief Implements -Wsign-compare.
5399 ///
5400 /// \param E the binary operator to check for warnings
5401 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
5402   // The type the comparison is being performed in.
5403   QualType T = E->getLHS()->getType();
5404   assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5405          && "comparison with mismatched types");
5406   if (E->isValueDependent())
5407     return AnalyzeImpConvsInComparison(S, E);
5408 
5409   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5410   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
5411 
5412   bool IsComparisonConstant = false;
5413 
5414   // Check whether an integer constant comparison results in a value
5415   // of 'true' or 'false'.
5416   if (T->isIntegralType(S.Context)) {
5417     llvm::APSInt RHSValue;
5418     bool IsRHSIntegralLiteral =
5419       RHS->isIntegerConstantExpr(RHSValue, S.Context);
5420     llvm::APSInt LHSValue;
5421     bool IsLHSIntegralLiteral =
5422       LHS->isIntegerConstantExpr(LHSValue, S.Context);
5423     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5424         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5425     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5426       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5427     else
5428       IsComparisonConstant =
5429         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
5430   } else if (!T->hasUnsignedIntegerRepresentation())
5431       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
5432 
5433   // We don't do anything special if this isn't an unsigned integral
5434   // comparison:  we're only interested in integral comparisons, and
5435   // signed comparisons only happen in cases we don't care to warn about.
5436   //
5437   // We also don't care about value-dependent expressions or expressions
5438   // whose result is a constant.
5439   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
5440     return AnalyzeImpConvsInComparison(S, E);
5441 
5442   // Check to see if one of the (unmodified) operands is of different
5443   // signedness.
5444   Expr *signedOperand, *unsignedOperand;
5445   if (LHS->getType()->hasSignedIntegerRepresentation()) {
5446     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
5447            "unsigned comparison between two signed integer expressions?");
5448     signedOperand = LHS;
5449     unsignedOperand = RHS;
5450   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5451     signedOperand = RHS;
5452     unsignedOperand = LHS;
5453   } else {
5454     CheckTrivialUnsignedComparison(S, E);
5455     return AnalyzeImpConvsInComparison(S, E);
5456   }
5457 
5458   // Otherwise, calculate the effective range of the signed operand.
5459   IntRange signedRange = GetExprRange(S.Context, signedOperand);
5460 
5461   // Go ahead and analyze implicit conversions in the operands.  Note
5462   // that we skip the implicit conversions on both sides.
5463   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5464   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
5465 
5466   // If the signed range is non-negative, -Wsign-compare won't fire,
5467   // but we should still check for comparisons which are always true
5468   // or false.
5469   if (signedRange.NonNegative)
5470     return CheckTrivialUnsignedComparison(S, E);
5471 
5472   // For (in)equality comparisons, if the unsigned operand is a
5473   // constant which cannot collide with a overflowed signed operand,
5474   // then reinterpreting the signed operand as unsigned will not
5475   // change the result of the comparison.
5476   if (E->isEqualityOp()) {
5477     unsigned comparisonWidth = S.Context.getIntWidth(T);
5478     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
5479 
5480     // We should never be unable to prove that the unsigned operand is
5481     // non-negative.
5482     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5483 
5484     if (unsignedRange.Width < comparisonWidth)
5485       return;
5486   }
5487 
5488   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5489     S.PDiag(diag::warn_mixed_sign_comparison)
5490       << LHS->getType() << RHS->getType()
5491       << LHS->getSourceRange() << RHS->getSourceRange());
5492 }
5493 
5494 /// Analyzes an attempt to assign the given value to a bitfield.
5495 ///
5496 /// Returns true if there was something fishy about the attempt.
5497 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5498                                       SourceLocation InitLoc) {
5499   assert(Bitfield->isBitField());
5500   if (Bitfield->isInvalidDecl())
5501     return false;
5502 
5503   // White-list bool bitfields.
5504   if (Bitfield->getType()->isBooleanType())
5505     return false;
5506 
5507   // Ignore value- or type-dependent expressions.
5508   if (Bitfield->getBitWidth()->isValueDependent() ||
5509       Bitfield->getBitWidth()->isTypeDependent() ||
5510       Init->isValueDependent() ||
5511       Init->isTypeDependent())
5512     return false;
5513 
5514   Expr *OriginalInit = Init->IgnoreParenImpCasts();
5515 
5516   llvm::APSInt Value;
5517   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
5518     return false;
5519 
5520   unsigned OriginalWidth = Value.getBitWidth();
5521   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
5522 
5523   if (OriginalWidth <= FieldWidth)
5524     return false;
5525 
5526   // Compute the value which the bitfield will contain.
5527   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
5528   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
5529 
5530   // Check whether the stored value is equal to the original value.
5531   TruncatedValue = TruncatedValue.extend(OriginalWidth);
5532   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
5533     return false;
5534 
5535   // Special-case bitfields of width 1: booleans are naturally 0/1, and
5536   // therefore don't strictly fit into a signed bitfield of width 1.
5537   if (FieldWidth == 1 && Value == 1)
5538     return false;
5539 
5540   std::string PrettyValue = Value.toString(10);
5541   std::string PrettyTrunc = TruncatedValue.toString(10);
5542 
5543   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5544     << PrettyValue << PrettyTrunc << OriginalInit->getType()
5545     << Init->getSourceRange();
5546 
5547   return true;
5548 }
5549 
5550 /// Analyze the given simple or compound assignment for warning-worthy
5551 /// operations.
5552 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
5553   // Just recurse on the LHS.
5554   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5555 
5556   // We want to recurse on the RHS as normal unless we're assigning to
5557   // a bitfield.
5558   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
5559     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
5560                                   E->getOperatorLoc())) {
5561       // Recurse, ignoring any implicit conversions on the RHS.
5562       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5563                                         E->getOperatorLoc());
5564     }
5565   }
5566 
5567   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5568 }
5569 
5570 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
5571 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
5572                             SourceLocation CContext, unsigned diag,
5573                             bool pruneControlFlow = false) {
5574   if (pruneControlFlow) {
5575     S.DiagRuntimeBehavior(E->getExprLoc(), E,
5576                           S.PDiag(diag)
5577                             << SourceType << T << E->getSourceRange()
5578                             << SourceRange(CContext));
5579     return;
5580   }
5581   S.Diag(E->getExprLoc(), diag)
5582     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5583 }
5584 
5585 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
5586 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
5587                             SourceLocation CContext, unsigned diag,
5588                             bool pruneControlFlow = false) {
5589   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
5590 }
5591 
5592 /// Diagnose an implicit cast from a literal expression. Does not warn when the
5593 /// cast wouldn't lose information.
5594 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5595                                     SourceLocation CContext) {
5596   // Try to convert the literal exactly to an integer. If we can, don't warn.
5597   bool isExact = false;
5598   const llvm::APFloat &Value = FL->getValue();
5599   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5600                             T->hasUnsignedIntegerRepresentation());
5601   if (Value.convertToInteger(IntegerValue,
5602                              llvm::APFloat::rmTowardZero, &isExact)
5603       == llvm::APFloat::opOK && isExact)
5604     return;
5605 
5606   // FIXME: Force the precision of the source value down so we don't print
5607   // digits which are usually useless (we don't really care here if we
5608   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
5609   // would automatically print the shortest representation, but it's a bit
5610   // tricky to implement.
5611   SmallString<16> PrettySourceValue;
5612   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5613   precision = (precision * 59 + 195) / 196;
5614   Value.toString(PrettySourceValue, precision);
5615 
5616   SmallString<16> PrettyTargetValue;
5617   if (T->isSpecificBuiltinType(BuiltinType::Bool))
5618     PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5619   else
5620     IntegerValue.toString(PrettyTargetValue);
5621 
5622   S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
5623     << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5624     << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
5625 }
5626 
5627 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5628   if (!Range.Width) return "0";
5629 
5630   llvm::APSInt ValueInRange = Value;
5631   ValueInRange.setIsSigned(!Range.NonNegative);
5632   ValueInRange = ValueInRange.trunc(Range.Width);
5633   return ValueInRange.toString(10);
5634 }
5635 
5636 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5637   if (!isa<ImplicitCastExpr>(Ex))
5638     return false;
5639 
5640   Expr *InnerE = Ex->IgnoreParenImpCasts();
5641   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5642   const Type *Source =
5643     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5644   if (Target->isDependentType())
5645     return false;
5646 
5647   const BuiltinType *FloatCandidateBT =
5648     dyn_cast<BuiltinType>(ToBool ? Source : Target);
5649   const Type *BoolCandidateType = ToBool ? Target : Source;
5650 
5651   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5652           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5653 }
5654 
5655 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5656                                       SourceLocation CC) {
5657   unsigned NumArgs = TheCall->getNumArgs();
5658   for (unsigned i = 0; i < NumArgs; ++i) {
5659     Expr *CurrA = TheCall->getArg(i);
5660     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5661       continue;
5662 
5663     bool IsSwapped = ((i > 0) &&
5664         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5665     IsSwapped |= ((i < (NumArgs - 1)) &&
5666         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5667     if (IsSwapped) {
5668       // Warn on this floating-point to bool conversion.
5669       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5670                       CurrA->getType(), CC,
5671                       diag::warn_impcast_floating_point_to_bool);
5672     }
5673   }
5674 }
5675 
5676 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
5677                              SourceLocation CC, bool *ICContext = 0) {
5678   if (E->isTypeDependent() || E->isValueDependent()) return;
5679 
5680   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5681   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5682   if (Source == Target) return;
5683   if (Target->isDependentType()) return;
5684 
5685   // If the conversion context location is invalid don't complain. We also
5686   // don't want to emit a warning if the issue occurs from the expansion of
5687   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5688   // delay this check as long as possible. Once we detect we are in that
5689   // scenario, we just return.
5690   if (CC.isInvalid())
5691     return;
5692 
5693   // Diagnose implicit casts to bool.
5694   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5695     if (isa<StringLiteral>(E))
5696       // Warn on string literal to bool.  Checks for string literals in logical
5697       // and expressions, for instance, assert(0 && "error here"), are
5698       // prevented by a check in AnalyzeImplicitConversions().
5699       return DiagnoseImpCast(S, E, T, CC,
5700                              diag::warn_impcast_string_literal_to_bool);
5701     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5702         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5703       // This covers the literal expressions that evaluate to Objective-C
5704       // objects.
5705       return DiagnoseImpCast(S, E, T, CC,
5706                              diag::warn_impcast_objective_c_literal_to_bool);
5707     }
5708     if (Source->isPointerType() || Source->canDecayToPointerType()) {
5709       // Warn on pointer to bool conversion that is always true.
5710       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5711                                      SourceRange(CC));
5712     }
5713   }
5714 
5715   // Strip vector types.
5716   if (isa<VectorType>(Source)) {
5717     if (!isa<VectorType>(Target)) {
5718       if (S.SourceMgr.isInSystemMacro(CC))
5719         return;
5720       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
5721     }
5722 
5723     // If the vector cast is cast between two vectors of the same size, it is
5724     // a bitcast, not a conversion.
5725     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5726       return;
5727 
5728     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5729     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5730   }
5731 
5732   // Strip complex types.
5733   if (isa<ComplexType>(Source)) {
5734     if (!isa<ComplexType>(Target)) {
5735       if (S.SourceMgr.isInSystemMacro(CC))
5736         return;
5737 
5738       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
5739     }
5740 
5741     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5742     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5743   }
5744 
5745   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5746   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5747 
5748   // If the source is floating point...
5749   if (SourceBT && SourceBT->isFloatingPoint()) {
5750     // ...and the target is floating point...
5751     if (TargetBT && TargetBT->isFloatingPoint()) {
5752       // ...then warn if we're dropping FP rank.
5753 
5754       // Builtin FP kinds are ordered by increasing FP rank.
5755       if (SourceBT->getKind() > TargetBT->getKind()) {
5756         // Don't warn about float constants that are precisely
5757         // representable in the target type.
5758         Expr::EvalResult result;
5759         if (E->EvaluateAsRValue(result, S.Context)) {
5760           // Value might be a float, a float vector, or a float complex.
5761           if (IsSameFloatAfterCast(result.Val,
5762                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5763                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
5764             return;
5765         }
5766 
5767         if (S.SourceMgr.isInSystemMacro(CC))
5768           return;
5769 
5770         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
5771       }
5772       return;
5773     }
5774 
5775     // If the target is integral, always warn.
5776     if (TargetBT && TargetBT->isInteger()) {
5777       if (S.SourceMgr.isInSystemMacro(CC))
5778         return;
5779 
5780       Expr *InnerE = E->IgnoreParenImpCasts();
5781       // We also want to warn on, e.g., "int i = -1.234"
5782       if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5783         if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5784           InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5785 
5786       if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5787         DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
5788       } else {
5789         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5790       }
5791     }
5792 
5793     // If the target is bool, warn if expr is a function or method call.
5794     if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5795         isa<CallExpr>(E)) {
5796       // Check last argument of function call to see if it is an
5797       // implicit cast from a type matching the type the result
5798       // is being cast to.
5799       CallExpr *CEx = cast<CallExpr>(E);
5800       unsigned NumArgs = CEx->getNumArgs();
5801       if (NumArgs > 0) {
5802         Expr *LastA = CEx->getArg(NumArgs - 1);
5803         Expr *InnerE = LastA->IgnoreParenImpCasts();
5804         const Type *InnerType =
5805           S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5806         if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5807           // Warn on this floating-point to bool conversion
5808           DiagnoseImpCast(S, E, T, CC,
5809                           diag::warn_impcast_floating_point_to_bool);
5810         }
5811       }
5812     }
5813     return;
5814   }
5815 
5816   if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
5817            == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
5818       && !Target->isBlockPointerType() && !Target->isMemberPointerType()
5819       && Target->isScalarType() && !Target->isNullPtrType()) {
5820     SourceLocation Loc = E->getSourceRange().getBegin();
5821     if (Loc.isMacroID())
5822       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
5823     if (!Loc.isMacroID() || CC.isMacroID())
5824       S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5825           << T << clang::SourceRange(CC)
5826           << FixItHint::CreateReplacement(Loc,
5827                                           S.getFixItZeroLiteralForType(T, Loc));
5828   }
5829 
5830   if (!Source->isIntegerType() || !Target->isIntegerType())
5831     return;
5832 
5833   // TODO: remove this early return once the false positives for constant->bool
5834   // in templates, macros, etc, are reduced or removed.
5835   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5836     return;
5837 
5838   IntRange SourceRange = GetExprRange(S.Context, E);
5839   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
5840 
5841   if (SourceRange.Width > TargetRange.Width) {
5842     // If the source is a constant, use a default-on diagnostic.
5843     // TODO: this should happen for bitfield stores, too.
5844     llvm::APSInt Value(32);
5845     if (E->isIntegerConstantExpr(Value, S.Context)) {
5846       if (S.SourceMgr.isInSystemMacro(CC))
5847         return;
5848 
5849       std::string PrettySourceValue = Value.toString(10);
5850       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
5851 
5852       S.DiagRuntimeBehavior(E->getExprLoc(), E,
5853         S.PDiag(diag::warn_impcast_integer_precision_constant)
5854             << PrettySourceValue << PrettyTargetValue
5855             << E->getType() << T << E->getSourceRange()
5856             << clang::SourceRange(CC));
5857       return;
5858     }
5859 
5860     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5861     if (S.SourceMgr.isInSystemMacro(CC))
5862       return;
5863 
5864     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
5865       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5866                              /* pruneControlFlow */ true);
5867     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
5868   }
5869 
5870   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5871       (!TargetRange.NonNegative && SourceRange.NonNegative &&
5872        SourceRange.Width == TargetRange.Width)) {
5873 
5874     if (S.SourceMgr.isInSystemMacro(CC))
5875       return;
5876 
5877     unsigned DiagID = diag::warn_impcast_integer_sign;
5878 
5879     // Traditionally, gcc has warned about this under -Wsign-compare.
5880     // We also want to warn about it in -Wconversion.
5881     // So if -Wconversion is off, use a completely identical diagnostic
5882     // in the sign-compare group.
5883     // The conditional-checking code will
5884     if (ICContext) {
5885       DiagID = diag::warn_impcast_integer_sign_conditional;
5886       *ICContext = true;
5887     }
5888 
5889     return DiagnoseImpCast(S, E, T, CC, DiagID);
5890   }
5891 
5892   // Diagnose conversions between different enumeration types.
5893   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5894   // type, to give us better diagnostics.
5895   QualType SourceType = E->getType();
5896   if (!S.getLangOpts().CPlusPlus) {
5897     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5898       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5899         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5900         SourceType = S.Context.getTypeDeclType(Enum);
5901         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5902       }
5903   }
5904 
5905   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5906     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
5907       if (SourceEnum->getDecl()->hasNameForLinkage() &&
5908           TargetEnum->getDecl()->hasNameForLinkage() &&
5909           SourceEnum != TargetEnum) {
5910         if (S.SourceMgr.isInSystemMacro(CC))
5911           return;
5912 
5913         return DiagnoseImpCast(S, E, SourceType, T, CC,
5914                                diag::warn_impcast_different_enum_types);
5915       }
5916 
5917   return;
5918 }
5919 
5920 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5921                               SourceLocation CC, QualType T);
5922 
5923 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
5924                              SourceLocation CC, bool &ICContext) {
5925   E = E->IgnoreParenImpCasts();
5926 
5927   if (isa<ConditionalOperator>(E))
5928     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
5929 
5930   AnalyzeImplicitConversions(S, E, CC);
5931   if (E->getType() != T)
5932     return CheckImplicitConversion(S, E, T, CC, &ICContext);
5933   return;
5934 }
5935 
5936 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5937                               SourceLocation CC, QualType T) {
5938   AnalyzeImplicitConversions(S, E->getCond(), CC);
5939 
5940   bool Suspicious = false;
5941   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5942   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
5943 
5944   // If -Wconversion would have warned about either of the candidates
5945   // for a signedness conversion to the context type...
5946   if (!Suspicious) return;
5947 
5948   // ...but it's currently ignored...
5949   if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5950                                  CC))
5951     return;
5952 
5953   // ...then check whether it would have warned about either of the
5954   // candidates for a signedness conversion to the condition type.
5955   if (E->getType() == T) return;
5956 
5957   Suspicious = false;
5958   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5959                           E->getType(), CC, &Suspicious);
5960   if (!Suspicious)
5961     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
5962                             E->getType(), CC, &Suspicious);
5963 }
5964 
5965 /// AnalyzeImplicitConversions - Find and report any interesting
5966 /// implicit conversions in the given expression.  There are a couple
5967 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
5968 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
5969   QualType T = OrigE->getType();
5970   Expr *E = OrigE->IgnoreParenImpCasts();
5971 
5972   if (E->isTypeDependent() || E->isValueDependent())
5973     return;
5974 
5975   // For conditional operators, we analyze the arguments as if they
5976   // were being fed directly into the output.
5977   if (isa<ConditionalOperator>(E)) {
5978     ConditionalOperator *CO = cast<ConditionalOperator>(E);
5979     CheckConditionalOperator(S, CO, CC, T);
5980     return;
5981   }
5982 
5983   // Check implicit argument conversions for function calls.
5984   if (CallExpr *Call = dyn_cast<CallExpr>(E))
5985     CheckImplicitArgumentConversions(S, Call, CC);
5986 
5987   // Go ahead and check any implicit conversions we might have skipped.
5988   // The non-canonical typecheck is just an optimization;
5989   // CheckImplicitConversion will filter out dead implicit conversions.
5990   if (E->getType() != T)
5991     CheckImplicitConversion(S, E, T, CC);
5992 
5993   // Now continue drilling into this expression.
5994 
5995   if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
5996     if (POE->getResultExpr())
5997       E = POE->getResultExpr();
5998   }
5999 
6000   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6001     return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6002 
6003   // Skip past explicit casts.
6004   if (isa<ExplicitCastExpr>(E)) {
6005     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
6006     return AnalyzeImplicitConversions(S, E, CC);
6007   }
6008 
6009   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6010     // Do a somewhat different check with comparison operators.
6011     if (BO->isComparisonOp())
6012       return AnalyzeComparison(S, BO);
6013 
6014     // And with simple assignments.
6015     if (BO->getOpcode() == BO_Assign)
6016       return AnalyzeAssignment(S, BO);
6017   }
6018 
6019   // These break the otherwise-useful invariant below.  Fortunately,
6020   // we don't really need to recurse into them, because any internal
6021   // expressions should have been analyzed already when they were
6022   // built into statements.
6023   if (isa<StmtExpr>(E)) return;
6024 
6025   // Don't descend into unevaluated contexts.
6026   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
6027 
6028   // Now just recurse over the expression's children.
6029   CC = E->getExprLoc();
6030   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
6031   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
6032   for (Stmt::child_range I = E->children(); I; ++I) {
6033     Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
6034     if (!ChildExpr)
6035       continue;
6036 
6037     if (IsLogicalAndOperator &&
6038         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
6039       // Ignore checking string literals that are in logical and operators.
6040       // This is a common pattern for asserts.
6041       continue;
6042     AnalyzeImplicitConversions(S, ChildExpr, CC);
6043   }
6044 }
6045 
6046 } // end anonymous namespace
6047 
6048 enum {
6049   AddressOf,
6050   FunctionPointer,
6051   ArrayPointer
6052 };
6053 
6054 /// \brief Diagnose pointers that are always non-null.
6055 /// \param E the expression containing the pointer
6056 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6057 /// compared to a null pointer
6058 /// \param IsEqual True when the comparison is equal to a null pointer
6059 /// \param Range Extra SourceRange to highlight in the diagnostic
6060 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6061                                         Expr::NullPointerConstantKind NullKind,
6062                                         bool IsEqual, SourceRange Range) {
6063 
6064   // Don't warn inside macros.
6065   if (E->getExprLoc().isMacroID())
6066       return;
6067   E = E->IgnoreImpCasts();
6068 
6069   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6070 
6071   bool IsAddressOf = false;
6072 
6073   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6074     if (UO->getOpcode() != UO_AddrOf)
6075       return;
6076     IsAddressOf = true;
6077     E = UO->getSubExpr();
6078   }
6079 
6080   // Expect to find a single Decl.  Skip anything more complicated.
6081   ValueDecl *D = 0;
6082   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6083     D = R->getDecl();
6084   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6085     D = M->getMemberDecl();
6086   }
6087 
6088   // Weak Decls can be null.
6089   if (!D || D->isWeak())
6090     return;
6091 
6092   QualType T = D->getType();
6093   const bool IsArray = T->isArrayType();
6094   const bool IsFunction = T->isFunctionType();
6095 
6096   if (IsAddressOf) {
6097     // Address of function is used to silence the function warning.
6098     if (IsFunction)
6099       return;
6100     // Address of reference can be null.
6101     if (T->isReferenceType())
6102       return;
6103   }
6104 
6105   // Found nothing.
6106   if (!IsAddressOf && !IsFunction && !IsArray)
6107     return;
6108 
6109   // Pretty print the expression for the diagnostic.
6110   std::string Str;
6111   llvm::raw_string_ostream S(Str);
6112   E->printPretty(S, 0, getPrintingPolicy());
6113 
6114   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6115                               : diag::warn_impcast_pointer_to_bool;
6116   unsigned DiagType;
6117   if (IsAddressOf)
6118     DiagType = AddressOf;
6119   else if (IsFunction)
6120     DiagType = FunctionPointer;
6121   else if (IsArray)
6122     DiagType = ArrayPointer;
6123   else
6124     llvm_unreachable("Could not determine diagnostic.");
6125   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6126                                 << Range << IsEqual;
6127 
6128   if (!IsFunction)
6129     return;
6130 
6131   // Suggest '&' to silence the function warning.
6132   Diag(E->getExprLoc(), diag::note_function_warning_silence)
6133       << FixItHint::CreateInsertion(E->getLocStart(), "&");
6134 
6135   // Check to see if '()' fixit should be emitted.
6136   QualType ReturnType;
6137   UnresolvedSet<4> NonTemplateOverloads;
6138   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6139   if (ReturnType.isNull())
6140     return;
6141 
6142   if (IsCompare) {
6143     // There are two cases here.  If there is null constant, the only suggest
6144     // for a pointer return type.  If the null is 0, then suggest if the return
6145     // type is a pointer or an integer type.
6146     if (!ReturnType->isPointerType()) {
6147       if (NullKind == Expr::NPCK_ZeroExpression ||
6148           NullKind == Expr::NPCK_ZeroLiteral) {
6149         if (!ReturnType->isIntegerType())
6150           return;
6151       } else {
6152         return;
6153       }
6154     }
6155   } else { // !IsCompare
6156     // For function to bool, only suggest if the function pointer has bool
6157     // return type.
6158     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6159       return;
6160   }
6161   Diag(E->getExprLoc(), diag::note_function_to_function_call)
6162       << FixItHint::CreateInsertion(
6163              getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
6164 }
6165 
6166 
6167 /// Diagnoses "dangerous" implicit conversions within the given
6168 /// expression (which is a full expression).  Implements -Wconversion
6169 /// and -Wsign-compare.
6170 ///
6171 /// \param CC the "context" location of the implicit conversion, i.e.
6172 ///   the most location of the syntactic entity requiring the implicit
6173 ///   conversion
6174 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
6175   // Don't diagnose in unevaluated contexts.
6176   if (isUnevaluatedContext())
6177     return;
6178 
6179   // Don't diagnose for value- or type-dependent expressions.
6180   if (E->isTypeDependent() || E->isValueDependent())
6181     return;
6182 
6183   // Check for array bounds violations in cases where the check isn't triggered
6184   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6185   // ArraySubscriptExpr is on the RHS of a variable initialization.
6186   CheckArrayAccess(E);
6187 
6188   // This is not the right CC for (e.g.) a variable initialization.
6189   AnalyzeImplicitConversions(*this, E, CC);
6190 }
6191 
6192 /// Diagnose when expression is an integer constant expression and its evaluation
6193 /// results in integer overflow
6194 void Sema::CheckForIntOverflow (Expr *E) {
6195   if (isa<BinaryOperator>(E->IgnoreParens()))
6196     E->EvaluateForOverflow(Context);
6197 }
6198 
6199 namespace {
6200 /// \brief Visitor for expressions which looks for unsequenced operations on the
6201 /// same object.
6202 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
6203   typedef EvaluatedExprVisitor<SequenceChecker> Base;
6204 
6205   /// \brief A tree of sequenced regions within an expression. Two regions are
6206   /// unsequenced if one is an ancestor or a descendent of the other. When we
6207   /// finish processing an expression with sequencing, such as a comma
6208   /// expression, we fold its tree nodes into its parent, since they are
6209   /// unsequenced with respect to nodes we will visit later.
6210   class SequenceTree {
6211     struct Value {
6212       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6213       unsigned Parent : 31;
6214       bool Merged : 1;
6215     };
6216     SmallVector<Value, 8> Values;
6217 
6218   public:
6219     /// \brief A region within an expression which may be sequenced with respect
6220     /// to some other region.
6221     class Seq {
6222       explicit Seq(unsigned N) : Index(N) {}
6223       unsigned Index;
6224       friend class SequenceTree;
6225     public:
6226       Seq() : Index(0) {}
6227     };
6228 
6229     SequenceTree() { Values.push_back(Value(0)); }
6230     Seq root() const { return Seq(0); }
6231 
6232     /// \brief Create a new sequence of operations, which is an unsequenced
6233     /// subset of \p Parent. This sequence of operations is sequenced with
6234     /// respect to other children of \p Parent.
6235     Seq allocate(Seq Parent) {
6236       Values.push_back(Value(Parent.Index));
6237       return Seq(Values.size() - 1);
6238     }
6239 
6240     /// \brief Merge a sequence of operations into its parent.
6241     void merge(Seq S) {
6242       Values[S.Index].Merged = true;
6243     }
6244 
6245     /// \brief Determine whether two operations are unsequenced. This operation
6246     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6247     /// should have been merged into its parent as appropriate.
6248     bool isUnsequenced(Seq Cur, Seq Old) {
6249       unsigned C = representative(Cur.Index);
6250       unsigned Target = representative(Old.Index);
6251       while (C >= Target) {
6252         if (C == Target)
6253           return true;
6254         C = Values[C].Parent;
6255       }
6256       return false;
6257     }
6258 
6259   private:
6260     /// \brief Pick a representative for a sequence.
6261     unsigned representative(unsigned K) {
6262       if (Values[K].Merged)
6263         // Perform path compression as we go.
6264         return Values[K].Parent = representative(Values[K].Parent);
6265       return K;
6266     }
6267   };
6268 
6269   /// An object for which we can track unsequenced uses.
6270   typedef NamedDecl *Object;
6271 
6272   /// Different flavors of object usage which we track. We only track the
6273   /// least-sequenced usage of each kind.
6274   enum UsageKind {
6275     /// A read of an object. Multiple unsequenced reads are OK.
6276     UK_Use,
6277     /// A modification of an object which is sequenced before the value
6278     /// computation of the expression, such as ++n in C++.
6279     UK_ModAsValue,
6280     /// A modification of an object which is not sequenced before the value
6281     /// computation of the expression, such as n++.
6282     UK_ModAsSideEffect,
6283 
6284     UK_Count = UK_ModAsSideEffect + 1
6285   };
6286 
6287   struct Usage {
6288     Usage() : Use(0), Seq() {}
6289     Expr *Use;
6290     SequenceTree::Seq Seq;
6291   };
6292 
6293   struct UsageInfo {
6294     UsageInfo() : Diagnosed(false) {}
6295     Usage Uses[UK_Count];
6296     /// Have we issued a diagnostic for this variable already?
6297     bool Diagnosed;
6298   };
6299   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6300 
6301   Sema &SemaRef;
6302   /// Sequenced regions within the expression.
6303   SequenceTree Tree;
6304   /// Declaration modifications and references which we have seen.
6305   UsageInfoMap UsageMap;
6306   /// The region we are currently within.
6307   SequenceTree::Seq Region;
6308   /// Filled in with declarations which were modified as a side-effect
6309   /// (that is, post-increment operations).
6310   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
6311   /// Expressions to check later. We defer checking these to reduce
6312   /// stack usage.
6313   SmallVectorImpl<Expr *> &WorkList;
6314 
6315   /// RAII object wrapping the visitation of a sequenced subexpression of an
6316   /// expression. At the end of this process, the side-effects of the evaluation
6317   /// become sequenced with respect to the value computation of the result, so
6318   /// we downgrade any UK_ModAsSideEffect within the evaluation to
6319   /// UK_ModAsValue.
6320   struct SequencedSubexpression {
6321     SequencedSubexpression(SequenceChecker &Self)
6322       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6323       Self.ModAsSideEffect = &ModAsSideEffect;
6324     }
6325     ~SequencedSubexpression() {
6326       for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6327         UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6328         U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6329         Self.addUsage(U, ModAsSideEffect[I].first,
6330                       ModAsSideEffect[I].second.Use, UK_ModAsValue);
6331       }
6332       Self.ModAsSideEffect = OldModAsSideEffect;
6333     }
6334 
6335     SequenceChecker &Self;
6336     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6337     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
6338   };
6339 
6340   /// RAII object wrapping the visitation of a subexpression which we might
6341   /// choose to evaluate as a constant. If any subexpression is evaluated and
6342   /// found to be non-constant, this allows us to suppress the evaluation of
6343   /// the outer expression.
6344   class EvaluationTracker {
6345   public:
6346     EvaluationTracker(SequenceChecker &Self)
6347         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6348       Self.EvalTracker = this;
6349     }
6350     ~EvaluationTracker() {
6351       Self.EvalTracker = Prev;
6352       if (Prev)
6353         Prev->EvalOK &= EvalOK;
6354     }
6355 
6356     bool evaluate(const Expr *E, bool &Result) {
6357       if (!EvalOK || E->isValueDependent())
6358         return false;
6359       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6360       return EvalOK;
6361     }
6362 
6363   private:
6364     SequenceChecker &Self;
6365     EvaluationTracker *Prev;
6366     bool EvalOK;
6367   } *EvalTracker;
6368 
6369   /// \brief Find the object which is produced by the specified expression,
6370   /// if any.
6371   Object getObject(Expr *E, bool Mod) const {
6372     E = E->IgnoreParenCasts();
6373     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6374       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6375         return getObject(UO->getSubExpr(), Mod);
6376     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6377       if (BO->getOpcode() == BO_Comma)
6378         return getObject(BO->getRHS(), Mod);
6379       if (Mod && BO->isAssignmentOp())
6380         return getObject(BO->getLHS(), Mod);
6381     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6382       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6383       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6384         return ME->getMemberDecl();
6385     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6386       // FIXME: If this is a reference, map through to its value.
6387       return DRE->getDecl();
6388     return 0;
6389   }
6390 
6391   /// \brief Note that an object was modified or used by an expression.
6392   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6393     Usage &U = UI.Uses[UK];
6394     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6395       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6396         ModAsSideEffect->push_back(std::make_pair(O, U));
6397       U.Use = Ref;
6398       U.Seq = Region;
6399     }
6400   }
6401   /// \brief Check whether a modification or use conflicts with a prior usage.
6402   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6403                   bool IsModMod) {
6404     if (UI.Diagnosed)
6405       return;
6406 
6407     const Usage &U = UI.Uses[OtherKind];
6408     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6409       return;
6410 
6411     Expr *Mod = U.Use;
6412     Expr *ModOrUse = Ref;
6413     if (OtherKind == UK_Use)
6414       std::swap(Mod, ModOrUse);
6415 
6416     SemaRef.Diag(Mod->getExprLoc(),
6417                  IsModMod ? diag::warn_unsequenced_mod_mod
6418                           : diag::warn_unsequenced_mod_use)
6419       << O << SourceRange(ModOrUse->getExprLoc());
6420     UI.Diagnosed = true;
6421   }
6422 
6423   void notePreUse(Object O, Expr *Use) {
6424     UsageInfo &U = UsageMap[O];
6425     // Uses conflict with other modifications.
6426     checkUsage(O, U, Use, UK_ModAsValue, false);
6427   }
6428   void notePostUse(Object O, Expr *Use) {
6429     UsageInfo &U = UsageMap[O];
6430     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6431     addUsage(U, O, Use, UK_Use);
6432   }
6433 
6434   void notePreMod(Object O, Expr *Mod) {
6435     UsageInfo &U = UsageMap[O];
6436     // Modifications conflict with other modifications and with uses.
6437     checkUsage(O, U, Mod, UK_ModAsValue, true);
6438     checkUsage(O, U, Mod, UK_Use, false);
6439   }
6440   void notePostMod(Object O, Expr *Use, UsageKind UK) {
6441     UsageInfo &U = UsageMap[O];
6442     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6443     addUsage(U, O, Use, UK);
6444   }
6445 
6446 public:
6447   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
6448       : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
6449         WorkList(WorkList), EvalTracker(0) {
6450     Visit(E);
6451   }
6452 
6453   void VisitStmt(Stmt *S) {
6454     // Skip all statements which aren't expressions for now.
6455   }
6456 
6457   void VisitExpr(Expr *E) {
6458     // By default, just recurse to evaluated subexpressions.
6459     Base::VisitStmt(E);
6460   }
6461 
6462   void VisitCastExpr(CastExpr *E) {
6463     Object O = Object();
6464     if (E->getCastKind() == CK_LValueToRValue)
6465       O = getObject(E->getSubExpr(), false);
6466 
6467     if (O)
6468       notePreUse(O, E);
6469     VisitExpr(E);
6470     if (O)
6471       notePostUse(O, E);
6472   }
6473 
6474   void VisitBinComma(BinaryOperator *BO) {
6475     // C++11 [expr.comma]p1:
6476     //   Every value computation and side effect associated with the left
6477     //   expression is sequenced before every value computation and side
6478     //   effect associated with the right expression.
6479     SequenceTree::Seq LHS = Tree.allocate(Region);
6480     SequenceTree::Seq RHS = Tree.allocate(Region);
6481     SequenceTree::Seq OldRegion = Region;
6482 
6483     {
6484       SequencedSubexpression SeqLHS(*this);
6485       Region = LHS;
6486       Visit(BO->getLHS());
6487     }
6488 
6489     Region = RHS;
6490     Visit(BO->getRHS());
6491 
6492     Region = OldRegion;
6493 
6494     // Forget that LHS and RHS are sequenced. They are both unsequenced
6495     // with respect to other stuff.
6496     Tree.merge(LHS);
6497     Tree.merge(RHS);
6498   }
6499 
6500   void VisitBinAssign(BinaryOperator *BO) {
6501     // The modification is sequenced after the value computation of the LHS
6502     // and RHS, so check it before inspecting the operands and update the
6503     // map afterwards.
6504     Object O = getObject(BO->getLHS(), true);
6505     if (!O)
6506       return VisitExpr(BO);
6507 
6508     notePreMod(O, BO);
6509 
6510     // C++11 [expr.ass]p7:
6511     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6512     //   only once.
6513     //
6514     // Therefore, for a compound assignment operator, O is considered used
6515     // everywhere except within the evaluation of E1 itself.
6516     if (isa<CompoundAssignOperator>(BO))
6517       notePreUse(O, BO);
6518 
6519     Visit(BO->getLHS());
6520 
6521     if (isa<CompoundAssignOperator>(BO))
6522       notePostUse(O, BO);
6523 
6524     Visit(BO->getRHS());
6525 
6526     // C++11 [expr.ass]p1:
6527     //   the assignment is sequenced [...] before the value computation of the
6528     //   assignment expression.
6529     // C11 6.5.16/3 has no such rule.
6530     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6531                                                        : UK_ModAsSideEffect);
6532   }
6533   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6534     VisitBinAssign(CAO);
6535   }
6536 
6537   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6538   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6539   void VisitUnaryPreIncDec(UnaryOperator *UO) {
6540     Object O = getObject(UO->getSubExpr(), true);
6541     if (!O)
6542       return VisitExpr(UO);
6543 
6544     notePreMod(O, UO);
6545     Visit(UO->getSubExpr());
6546     // C++11 [expr.pre.incr]p1:
6547     //   the expression ++x is equivalent to x+=1
6548     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6549                                                        : UK_ModAsSideEffect);
6550   }
6551 
6552   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6553   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6554   void VisitUnaryPostIncDec(UnaryOperator *UO) {
6555     Object O = getObject(UO->getSubExpr(), true);
6556     if (!O)
6557       return VisitExpr(UO);
6558 
6559     notePreMod(O, UO);
6560     Visit(UO->getSubExpr());
6561     notePostMod(O, UO, UK_ModAsSideEffect);
6562   }
6563 
6564   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6565   void VisitBinLOr(BinaryOperator *BO) {
6566     // The side-effects of the LHS of an '&&' are sequenced before the
6567     // value computation of the RHS, and hence before the value computation
6568     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6569     // as if they were unconditionally sequenced.
6570     EvaluationTracker Eval(*this);
6571     {
6572       SequencedSubexpression Sequenced(*this);
6573       Visit(BO->getLHS());
6574     }
6575 
6576     bool Result;
6577     if (Eval.evaluate(BO->getLHS(), Result)) {
6578       if (!Result)
6579         Visit(BO->getRHS());
6580     } else {
6581       // Check for unsequenced operations in the RHS, treating it as an
6582       // entirely separate evaluation.
6583       //
6584       // FIXME: If there are operations in the RHS which are unsequenced
6585       // with respect to operations outside the RHS, and those operations
6586       // are unconditionally evaluated, diagnose them.
6587       WorkList.push_back(BO->getRHS());
6588     }
6589   }
6590   void VisitBinLAnd(BinaryOperator *BO) {
6591     EvaluationTracker Eval(*this);
6592     {
6593       SequencedSubexpression Sequenced(*this);
6594       Visit(BO->getLHS());
6595     }
6596 
6597     bool Result;
6598     if (Eval.evaluate(BO->getLHS(), Result)) {
6599       if (Result)
6600         Visit(BO->getRHS());
6601     } else {
6602       WorkList.push_back(BO->getRHS());
6603     }
6604   }
6605 
6606   // Only visit the condition, unless we can be sure which subexpression will
6607   // be chosen.
6608   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
6609     EvaluationTracker Eval(*this);
6610     {
6611       SequencedSubexpression Sequenced(*this);
6612       Visit(CO->getCond());
6613     }
6614 
6615     bool Result;
6616     if (Eval.evaluate(CO->getCond(), Result))
6617       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
6618     else {
6619       WorkList.push_back(CO->getTrueExpr());
6620       WorkList.push_back(CO->getFalseExpr());
6621     }
6622   }
6623 
6624   void VisitCallExpr(CallExpr *CE) {
6625     // C++11 [intro.execution]p15:
6626     //   When calling a function [...], every value computation and side effect
6627     //   associated with any argument expression, or with the postfix expression
6628     //   designating the called function, is sequenced before execution of every
6629     //   expression or statement in the body of the function [and thus before
6630     //   the value computation of its result].
6631     SequencedSubexpression Sequenced(*this);
6632     Base::VisitCallExpr(CE);
6633 
6634     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6635   }
6636 
6637   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
6638     // This is a call, so all subexpressions are sequenced before the result.
6639     SequencedSubexpression Sequenced(*this);
6640 
6641     if (!CCE->isListInitialization())
6642       return VisitExpr(CCE);
6643 
6644     // In C++11, list initializations are sequenced.
6645     SmallVector<SequenceTree::Seq, 32> Elts;
6646     SequenceTree::Seq Parent = Region;
6647     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6648                                         E = CCE->arg_end();
6649          I != E; ++I) {
6650       Region = Tree.allocate(Parent);
6651       Elts.push_back(Region);
6652       Visit(*I);
6653     }
6654 
6655     // Forget that the initializers are sequenced.
6656     Region = Parent;
6657     for (unsigned I = 0; I < Elts.size(); ++I)
6658       Tree.merge(Elts[I]);
6659   }
6660 
6661   void VisitInitListExpr(InitListExpr *ILE) {
6662     if (!SemaRef.getLangOpts().CPlusPlus11)
6663       return VisitExpr(ILE);
6664 
6665     // In C++11, list initializations are sequenced.
6666     SmallVector<SequenceTree::Seq, 32> Elts;
6667     SequenceTree::Seq Parent = Region;
6668     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6669       Expr *E = ILE->getInit(I);
6670       if (!E) continue;
6671       Region = Tree.allocate(Parent);
6672       Elts.push_back(Region);
6673       Visit(E);
6674     }
6675 
6676     // Forget that the initializers are sequenced.
6677     Region = Parent;
6678     for (unsigned I = 0; I < Elts.size(); ++I)
6679       Tree.merge(Elts[I]);
6680   }
6681 };
6682 }
6683 
6684 void Sema::CheckUnsequencedOperations(Expr *E) {
6685   SmallVector<Expr *, 8> WorkList;
6686   WorkList.push_back(E);
6687   while (!WorkList.empty()) {
6688     Expr *Item = WorkList.pop_back_val();
6689     SequenceChecker(*this, Item, WorkList);
6690   }
6691 }
6692 
6693 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6694                               bool IsConstexpr) {
6695   CheckImplicitConversions(E, CheckLoc);
6696   CheckUnsequencedOperations(E);
6697   if (!IsConstexpr && !E->isValueDependent())
6698     CheckForIntOverflow(E);
6699 }
6700 
6701 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6702                                        FieldDecl *BitField,
6703                                        Expr *Init) {
6704   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6705 }
6706 
6707 /// CheckParmsForFunctionDef - Check that the parameters of the given
6708 /// function are appropriate for the definition of a function. This
6709 /// takes care of any checks that cannot be performed on the
6710 /// declaration itself, e.g., that the types of each of the function
6711 /// parameters are complete.
6712 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6713                                     ParmVarDecl *const *PEnd,
6714                                     bool CheckParameterNames) {
6715   bool HasInvalidParm = false;
6716   for (; P != PEnd; ++P) {
6717     ParmVarDecl *Param = *P;
6718 
6719     // C99 6.7.5.3p4: the parameters in a parameter type list in a
6720     // function declarator that is part of a function definition of
6721     // that function shall not have incomplete type.
6722     //
6723     // This is also C++ [dcl.fct]p6.
6724     if (!Param->isInvalidDecl() &&
6725         RequireCompleteType(Param->getLocation(), Param->getType(),
6726                             diag::err_typecheck_decl_incomplete_type)) {
6727       Param->setInvalidDecl();
6728       HasInvalidParm = true;
6729     }
6730 
6731     // C99 6.9.1p5: If the declarator includes a parameter type list, the
6732     // declaration of each parameter shall include an identifier.
6733     if (CheckParameterNames &&
6734         Param->getIdentifier() == 0 &&
6735         !Param->isImplicit() &&
6736         !getLangOpts().CPlusPlus)
6737       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
6738 
6739     // C99 6.7.5.3p12:
6740     //   If the function declarator is not part of a definition of that
6741     //   function, parameters may have incomplete type and may use the [*]
6742     //   notation in their sequences of declarator specifiers to specify
6743     //   variable length array types.
6744     QualType PType = Param->getOriginalType();
6745     while (const ArrayType *AT = Context.getAsArrayType(PType)) {
6746       if (AT->getSizeModifier() == ArrayType::Star) {
6747         // FIXME: This diagnostic should point the '[*]' if source-location
6748         // information is added for it.
6749         Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
6750         break;
6751       }
6752       PType= AT->getElementType();
6753     }
6754 
6755     // MSVC destroys objects passed by value in the callee.  Therefore a
6756     // function definition which takes such a parameter must be able to call the
6757     // object's destructor.  However, we don't perform any direct access check
6758     // on the dtor.
6759     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6760                                        .getCXXABI()
6761                                        .areArgsDestroyedLeftToRightInCallee()) {
6762       if (!Param->isInvalidDecl()) {
6763         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6764           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6765           if (!ClassDecl->isInvalidDecl() &&
6766               !ClassDecl->hasIrrelevantDestructor() &&
6767               !ClassDecl->isDependentContext()) {
6768             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6769             MarkFunctionReferenced(Param->getLocation(), Destructor);
6770             DiagnoseUseOfDecl(Destructor, Param->getLocation());
6771           }
6772         }
6773       }
6774     }
6775   }
6776 
6777   return HasInvalidParm;
6778 }
6779 
6780 /// CheckCastAlign - Implements -Wcast-align, which warns when a
6781 /// pointer cast increases the alignment requirements.
6782 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6783   // This is actually a lot of work to potentially be doing on every
6784   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
6785   if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6786                                           TRange.getBegin())
6787         == DiagnosticsEngine::Ignored)
6788     return;
6789 
6790   // Ignore dependent types.
6791   if (T->isDependentType() || Op->getType()->isDependentType())
6792     return;
6793 
6794   // Require that the destination be a pointer type.
6795   const PointerType *DestPtr = T->getAs<PointerType>();
6796   if (!DestPtr) return;
6797 
6798   // If the destination has alignment 1, we're done.
6799   QualType DestPointee = DestPtr->getPointeeType();
6800   if (DestPointee->isIncompleteType()) return;
6801   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6802   if (DestAlign.isOne()) return;
6803 
6804   // Require that the source be a pointer type.
6805   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6806   if (!SrcPtr) return;
6807   QualType SrcPointee = SrcPtr->getPointeeType();
6808 
6809   // Whitelist casts from cv void*.  We already implicitly
6810   // whitelisted casts to cv void*, since they have alignment 1.
6811   // Also whitelist casts involving incomplete types, which implicitly
6812   // includes 'void'.
6813   if (SrcPointee->isIncompleteType()) return;
6814 
6815   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6816   if (SrcAlign >= DestAlign) return;
6817 
6818   Diag(TRange.getBegin(), diag::warn_cast_align)
6819     << Op->getType() << T
6820     << static_cast<unsigned>(SrcAlign.getQuantity())
6821     << static_cast<unsigned>(DestAlign.getQuantity())
6822     << TRange << Op->getSourceRange();
6823 }
6824 
6825 static const Type* getElementType(const Expr *BaseExpr) {
6826   const Type* EltType = BaseExpr->getType().getTypePtr();
6827   if (EltType->isAnyPointerType())
6828     return EltType->getPointeeType().getTypePtr();
6829   else if (EltType->isArrayType())
6830     return EltType->getBaseElementTypeUnsafe();
6831   return EltType;
6832 }
6833 
6834 /// \brief Check whether this array fits the idiom of a size-one tail padded
6835 /// array member of a struct.
6836 ///
6837 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
6838 /// commonly used to emulate flexible arrays in C89 code.
6839 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6840                                     const NamedDecl *ND) {
6841   if (Size != 1 || !ND) return false;
6842 
6843   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6844   if (!FD) return false;
6845 
6846   // Don't consider sizes resulting from macro expansions or template argument
6847   // substitution to form C89 tail-padded arrays.
6848 
6849   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
6850   while (TInfo) {
6851     TypeLoc TL = TInfo->getTypeLoc();
6852     // Look through typedefs.
6853     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6854       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
6855       TInfo = TDL->getTypeSourceInfo();
6856       continue;
6857     }
6858     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6859       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
6860       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6861         return false;
6862     }
6863     break;
6864   }
6865 
6866   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
6867   if (!RD) return false;
6868   if (RD->isUnion()) return false;
6869   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6870     if (!CRD->isStandardLayout()) return false;
6871   }
6872 
6873   // See if this is the last field decl in the record.
6874   const Decl *D = FD;
6875   while ((D = D->getNextDeclInContext()))
6876     if (isa<FieldDecl>(D))
6877       return false;
6878   return true;
6879 }
6880 
6881 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
6882                             const ArraySubscriptExpr *ASE,
6883                             bool AllowOnePastEnd, bool IndexNegated) {
6884   IndexExpr = IndexExpr->IgnoreParenImpCasts();
6885   if (IndexExpr->isValueDependent())
6886     return;
6887 
6888   const Type *EffectiveType = getElementType(BaseExpr);
6889   BaseExpr = BaseExpr->IgnoreParenCasts();
6890   const ConstantArrayType *ArrayTy =
6891     Context.getAsConstantArrayType(BaseExpr->getType());
6892   if (!ArrayTy)
6893     return;
6894 
6895   llvm::APSInt index;
6896   if (!IndexExpr->EvaluateAsInt(index, Context))
6897     return;
6898   if (IndexNegated)
6899     index = -index;
6900 
6901   const NamedDecl *ND = NULL;
6902   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6903     ND = dyn_cast<NamedDecl>(DRE->getDecl());
6904   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6905     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6906 
6907   if (index.isUnsigned() || !index.isNegative()) {
6908     llvm::APInt size = ArrayTy->getSize();
6909     if (!size.isStrictlyPositive())
6910       return;
6911 
6912     const Type* BaseType = getElementType(BaseExpr);
6913     if (BaseType != EffectiveType) {
6914       // Make sure we're comparing apples to apples when comparing index to size
6915       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6916       uint64_t array_typesize = Context.getTypeSize(BaseType);
6917       // Handle ptrarith_typesize being zero, such as when casting to void*
6918       if (!ptrarith_typesize) ptrarith_typesize = 1;
6919       if (ptrarith_typesize != array_typesize) {
6920         // There's a cast to a different size type involved
6921         uint64_t ratio = array_typesize / ptrarith_typesize;
6922         // TODO: Be smarter about handling cases where array_typesize is not a
6923         // multiple of ptrarith_typesize
6924         if (ptrarith_typesize * ratio == array_typesize)
6925           size *= llvm::APInt(size.getBitWidth(), ratio);
6926       }
6927     }
6928 
6929     if (size.getBitWidth() > index.getBitWidth())
6930       index = index.zext(size.getBitWidth());
6931     else if (size.getBitWidth() < index.getBitWidth())
6932       size = size.zext(index.getBitWidth());
6933 
6934     // For array subscripting the index must be less than size, but for pointer
6935     // arithmetic also allow the index (offset) to be equal to size since
6936     // computing the next address after the end of the array is legal and
6937     // commonly done e.g. in C++ iterators and range-based for loops.
6938     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
6939       return;
6940 
6941     // Also don't warn for arrays of size 1 which are members of some
6942     // structure. These are often used to approximate flexible arrays in C89
6943     // code.
6944     if (IsTailPaddedMemberArray(*this, size, ND))
6945       return;
6946 
6947     // Suppress the warning if the subscript expression (as identified by the
6948     // ']' location) and the index expression are both from macro expansions
6949     // within a system header.
6950     if (ASE) {
6951       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6952           ASE->getRBracketLoc());
6953       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6954         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6955             IndexExpr->getLocStart());
6956         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
6957           return;
6958       }
6959     }
6960 
6961     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
6962     if (ASE)
6963       DiagID = diag::warn_array_index_exceeds_bounds;
6964 
6965     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6966                         PDiag(DiagID) << index.toString(10, true)
6967                           << size.toString(10, true)
6968                           << (unsigned)size.getLimitedValue(~0U)
6969                           << IndexExpr->getSourceRange());
6970   } else {
6971     unsigned DiagID = diag::warn_array_index_precedes_bounds;
6972     if (!ASE) {
6973       DiagID = diag::warn_ptr_arith_precedes_bounds;
6974       if (index.isNegative()) index = -index;
6975     }
6976 
6977     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6978                         PDiag(DiagID) << index.toString(10, true)
6979                           << IndexExpr->getSourceRange());
6980   }
6981 
6982   if (!ND) {
6983     // Try harder to find a NamedDecl to point at in the note.
6984     while (const ArraySubscriptExpr *ASE =
6985            dyn_cast<ArraySubscriptExpr>(BaseExpr))
6986       BaseExpr = ASE->getBase()->IgnoreParenCasts();
6987     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6988       ND = dyn_cast<NamedDecl>(DRE->getDecl());
6989     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6990       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6991   }
6992 
6993   if (ND)
6994     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6995                         PDiag(diag::note_array_index_out_of_bounds)
6996                           << ND->getDeclName());
6997 }
6998 
6999 void Sema::CheckArrayAccess(const Expr *expr) {
7000   int AllowOnePastEnd = 0;
7001   while (expr) {
7002     expr = expr->IgnoreParenImpCasts();
7003     switch (expr->getStmtClass()) {
7004       case Stmt::ArraySubscriptExprClass: {
7005         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
7006         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
7007                          AllowOnePastEnd > 0);
7008         return;
7009       }
7010       case Stmt::UnaryOperatorClass: {
7011         // Only unwrap the * and & unary operators
7012         const UnaryOperator *UO = cast<UnaryOperator>(expr);
7013         expr = UO->getSubExpr();
7014         switch (UO->getOpcode()) {
7015           case UO_AddrOf:
7016             AllowOnePastEnd++;
7017             break;
7018           case UO_Deref:
7019             AllowOnePastEnd--;
7020             break;
7021           default:
7022             return;
7023         }
7024         break;
7025       }
7026       case Stmt::ConditionalOperatorClass: {
7027         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7028         if (const Expr *lhs = cond->getLHS())
7029           CheckArrayAccess(lhs);
7030         if (const Expr *rhs = cond->getRHS())
7031           CheckArrayAccess(rhs);
7032         return;
7033       }
7034       default:
7035         return;
7036     }
7037   }
7038 }
7039 
7040 //===--- CHECK: Objective-C retain cycles ----------------------------------//
7041 
7042 namespace {
7043   struct RetainCycleOwner {
7044     RetainCycleOwner() : Variable(0), Indirect(false) {}
7045     VarDecl *Variable;
7046     SourceRange Range;
7047     SourceLocation Loc;
7048     bool Indirect;
7049 
7050     void setLocsFrom(Expr *e) {
7051       Loc = e->getExprLoc();
7052       Range = e->getSourceRange();
7053     }
7054   };
7055 }
7056 
7057 /// Consider whether capturing the given variable can possibly lead to
7058 /// a retain cycle.
7059 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
7060   // In ARC, it's captured strongly iff the variable has __strong
7061   // lifetime.  In MRR, it's captured strongly if the variable is
7062   // __block and has an appropriate type.
7063   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7064     return false;
7065 
7066   owner.Variable = var;
7067   if (ref)
7068     owner.setLocsFrom(ref);
7069   return true;
7070 }
7071 
7072 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
7073   while (true) {
7074     e = e->IgnoreParens();
7075     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7076       switch (cast->getCastKind()) {
7077       case CK_BitCast:
7078       case CK_LValueBitCast:
7079       case CK_LValueToRValue:
7080       case CK_ARCReclaimReturnedObject:
7081         e = cast->getSubExpr();
7082         continue;
7083 
7084       default:
7085         return false;
7086       }
7087     }
7088 
7089     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7090       ObjCIvarDecl *ivar = ref->getDecl();
7091       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7092         return false;
7093 
7094       // Try to find a retain cycle in the base.
7095       if (!findRetainCycleOwner(S, ref->getBase(), owner))
7096         return false;
7097 
7098       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7099       owner.Indirect = true;
7100       return true;
7101     }
7102 
7103     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7104       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7105       if (!var) return false;
7106       return considerVariable(var, ref, owner);
7107     }
7108 
7109     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7110       if (member->isArrow()) return false;
7111 
7112       // Don't count this as an indirect ownership.
7113       e = member->getBase();
7114       continue;
7115     }
7116 
7117     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7118       // Only pay attention to pseudo-objects on property references.
7119       ObjCPropertyRefExpr *pre
7120         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7121                                               ->IgnoreParens());
7122       if (!pre) return false;
7123       if (pre->isImplicitProperty()) return false;
7124       ObjCPropertyDecl *property = pre->getExplicitProperty();
7125       if (!property->isRetaining() &&
7126           !(property->getPropertyIvarDecl() &&
7127             property->getPropertyIvarDecl()->getType()
7128               .getObjCLifetime() == Qualifiers::OCL_Strong))
7129           return false;
7130 
7131       owner.Indirect = true;
7132       if (pre->isSuperReceiver()) {
7133         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7134         if (!owner.Variable)
7135           return false;
7136         owner.Loc = pre->getLocation();
7137         owner.Range = pre->getSourceRange();
7138         return true;
7139       }
7140       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7141                               ->getSourceExpr());
7142       continue;
7143     }
7144 
7145     // Array ivars?
7146 
7147     return false;
7148   }
7149 }
7150 
7151 namespace {
7152   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7153     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7154       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
7155         Variable(variable), Capturer(0) {}
7156 
7157     VarDecl *Variable;
7158     Expr *Capturer;
7159 
7160     void VisitDeclRefExpr(DeclRefExpr *ref) {
7161       if (ref->getDecl() == Variable && !Capturer)
7162         Capturer = ref;
7163     }
7164 
7165     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7166       if (Capturer) return;
7167       Visit(ref->getBase());
7168       if (Capturer && ref->isFreeIvar())
7169         Capturer = ref;
7170     }
7171 
7172     void VisitBlockExpr(BlockExpr *block) {
7173       // Look inside nested blocks
7174       if (block->getBlockDecl()->capturesVariable(Variable))
7175         Visit(block->getBlockDecl()->getBody());
7176     }
7177 
7178     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7179       if (Capturer) return;
7180       if (OVE->getSourceExpr())
7181         Visit(OVE->getSourceExpr());
7182     }
7183   };
7184 }
7185 
7186 /// Check whether the given argument is a block which captures a
7187 /// variable.
7188 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7189   assert(owner.Variable && owner.Loc.isValid());
7190 
7191   e = e->IgnoreParenCasts();
7192 
7193   // Look through [^{...} copy] and Block_copy(^{...}).
7194   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7195     Selector Cmd = ME->getSelector();
7196     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7197       e = ME->getInstanceReceiver();
7198       if (!e)
7199         return 0;
7200       e = e->IgnoreParenCasts();
7201     }
7202   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7203     if (CE->getNumArgs() == 1) {
7204       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
7205       if (Fn) {
7206         const IdentifierInfo *FnI = Fn->getIdentifier();
7207         if (FnI && FnI->isStr("_Block_copy")) {
7208           e = CE->getArg(0)->IgnoreParenCasts();
7209         }
7210       }
7211     }
7212   }
7213 
7214   BlockExpr *block = dyn_cast<BlockExpr>(e);
7215   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
7216     return 0;
7217 
7218   FindCaptureVisitor visitor(S.Context, owner.Variable);
7219   visitor.Visit(block->getBlockDecl()->getBody());
7220   return visitor.Capturer;
7221 }
7222 
7223 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7224                                 RetainCycleOwner &owner) {
7225   assert(capturer);
7226   assert(owner.Variable && owner.Loc.isValid());
7227 
7228   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7229     << owner.Variable << capturer->getSourceRange();
7230   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7231     << owner.Indirect << owner.Range;
7232 }
7233 
7234 /// Check for a keyword selector that starts with the word 'add' or
7235 /// 'set'.
7236 static bool isSetterLikeSelector(Selector sel) {
7237   if (sel.isUnarySelector()) return false;
7238 
7239   StringRef str = sel.getNameForSlot(0);
7240   while (!str.empty() && str.front() == '_') str = str.substr(1);
7241   if (str.startswith("set"))
7242     str = str.substr(3);
7243   else if (str.startswith("add")) {
7244     // Specially whitelist 'addOperationWithBlock:'.
7245     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7246       return false;
7247     str = str.substr(3);
7248   }
7249   else
7250     return false;
7251 
7252   if (str.empty()) return true;
7253   return !isLowercase(str.front());
7254 }
7255 
7256 /// Check a message send to see if it's likely to cause a retain cycle.
7257 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7258   // Only check instance methods whose selector looks like a setter.
7259   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7260     return;
7261 
7262   // Try to find a variable that the receiver is strongly owned by.
7263   RetainCycleOwner owner;
7264   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
7265     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
7266       return;
7267   } else {
7268     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7269     owner.Variable = getCurMethodDecl()->getSelfDecl();
7270     owner.Loc = msg->getSuperLoc();
7271     owner.Range = msg->getSuperLoc();
7272   }
7273 
7274   // Check whether the receiver is captured by any of the arguments.
7275   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7276     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7277       return diagnoseRetainCycle(*this, capturer, owner);
7278 }
7279 
7280 /// Check a property assign to see if it's likely to cause a retain cycle.
7281 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7282   RetainCycleOwner owner;
7283   if (!findRetainCycleOwner(*this, receiver, owner))
7284     return;
7285 
7286   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7287     diagnoseRetainCycle(*this, capturer, owner);
7288 }
7289 
7290 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7291   RetainCycleOwner Owner;
7292   if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
7293     return;
7294 
7295   // Because we don't have an expression for the variable, we have to set the
7296   // location explicitly here.
7297   Owner.Loc = Var->getLocation();
7298   Owner.Range = Var->getSourceRange();
7299 
7300   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7301     diagnoseRetainCycle(*this, Capturer, Owner);
7302 }
7303 
7304 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7305                                      Expr *RHS, bool isProperty) {
7306   // Check if RHS is an Objective-C object literal, which also can get
7307   // immediately zapped in a weak reference.  Note that we explicitly
7308   // allow ObjCStringLiterals, since those are designed to never really die.
7309   RHS = RHS->IgnoreParenImpCasts();
7310 
7311   // This enum needs to match with the 'select' in
7312   // warn_objc_arc_literal_assign (off-by-1).
7313   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7314   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7315     return false;
7316 
7317   S.Diag(Loc, diag::warn_arc_literal_assign)
7318     << (unsigned) Kind
7319     << (isProperty ? 0 : 1)
7320     << RHS->getSourceRange();
7321 
7322   return true;
7323 }
7324 
7325 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7326                                     Qualifiers::ObjCLifetime LT,
7327                                     Expr *RHS, bool isProperty) {
7328   // Strip off any implicit cast added to get to the one ARC-specific.
7329   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7330     if (cast->getCastKind() == CK_ARCConsumeObject) {
7331       S.Diag(Loc, diag::warn_arc_retained_assign)
7332         << (LT == Qualifiers::OCL_ExplicitNone)
7333         << (isProperty ? 0 : 1)
7334         << RHS->getSourceRange();
7335       return true;
7336     }
7337     RHS = cast->getSubExpr();
7338   }
7339 
7340   if (LT == Qualifiers::OCL_Weak &&
7341       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7342     return true;
7343 
7344   return false;
7345 }
7346 
7347 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7348                               QualType LHS, Expr *RHS) {
7349   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7350 
7351   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7352     return false;
7353 
7354   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7355     return true;
7356 
7357   return false;
7358 }
7359 
7360 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7361                               Expr *LHS, Expr *RHS) {
7362   QualType LHSType;
7363   // PropertyRef on LHS type need be directly obtained from
7364   // its declaration as it has a PseudoType.
7365   ObjCPropertyRefExpr *PRE
7366     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7367   if (PRE && !PRE->isImplicitProperty()) {
7368     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7369     if (PD)
7370       LHSType = PD->getType();
7371   }
7372 
7373   if (LHSType.isNull())
7374     LHSType = LHS->getType();
7375 
7376   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7377 
7378   if (LT == Qualifiers::OCL_Weak) {
7379     DiagnosticsEngine::Level Level =
7380       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
7381     if (Level != DiagnosticsEngine::Ignored)
7382       getCurFunction()->markSafeWeakUse(LHS);
7383   }
7384 
7385   if (checkUnsafeAssigns(Loc, LHSType, RHS))
7386     return;
7387 
7388   // FIXME. Check for other life times.
7389   if (LT != Qualifiers::OCL_None)
7390     return;
7391 
7392   if (PRE) {
7393     if (PRE->isImplicitProperty())
7394       return;
7395     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7396     if (!PD)
7397       return;
7398 
7399     unsigned Attributes = PD->getPropertyAttributes();
7400     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
7401       // when 'assign' attribute was not explicitly specified
7402       // by user, ignore it and rely on property type itself
7403       // for lifetime info.
7404       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7405       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7406           LHSType->isObjCRetainableType())
7407         return;
7408 
7409       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7410         if (cast->getCastKind() == CK_ARCConsumeObject) {
7411           Diag(Loc, diag::warn_arc_retained_property_assign)
7412           << RHS->getSourceRange();
7413           return;
7414         }
7415         RHS = cast->getSubExpr();
7416       }
7417     }
7418     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
7419       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7420         return;
7421     }
7422   }
7423 }
7424 
7425 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7426 
7427 namespace {
7428 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7429                                  SourceLocation StmtLoc,
7430                                  const NullStmt *Body) {
7431   // Do not warn if the body is a macro that expands to nothing, e.g:
7432   //
7433   // #define CALL(x)
7434   // if (condition)
7435   //   CALL(0);
7436   //
7437   if (Body->hasLeadingEmptyMacro())
7438     return false;
7439 
7440   // Get line numbers of statement and body.
7441   bool StmtLineInvalid;
7442   unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7443                                                       &StmtLineInvalid);
7444   if (StmtLineInvalid)
7445     return false;
7446 
7447   bool BodyLineInvalid;
7448   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7449                                                       &BodyLineInvalid);
7450   if (BodyLineInvalid)
7451     return false;
7452 
7453   // Warn if null statement and body are on the same line.
7454   if (StmtLine != BodyLine)
7455     return false;
7456 
7457   return true;
7458 }
7459 } // Unnamed namespace
7460 
7461 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7462                                  const Stmt *Body,
7463                                  unsigned DiagID) {
7464   // Since this is a syntactic check, don't emit diagnostic for template
7465   // instantiations, this just adds noise.
7466   if (CurrentInstantiationScope)
7467     return;
7468 
7469   // The body should be a null statement.
7470   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7471   if (!NBody)
7472     return;
7473 
7474   // Do the usual checks.
7475   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7476     return;
7477 
7478   Diag(NBody->getSemiLoc(), DiagID);
7479   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7480 }
7481 
7482 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7483                                  const Stmt *PossibleBody) {
7484   assert(!CurrentInstantiationScope); // Ensured by caller
7485 
7486   SourceLocation StmtLoc;
7487   const Stmt *Body;
7488   unsigned DiagID;
7489   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7490     StmtLoc = FS->getRParenLoc();
7491     Body = FS->getBody();
7492     DiagID = diag::warn_empty_for_body;
7493   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7494     StmtLoc = WS->getCond()->getSourceRange().getEnd();
7495     Body = WS->getBody();
7496     DiagID = diag::warn_empty_while_body;
7497   } else
7498     return; // Neither `for' nor `while'.
7499 
7500   // The body should be a null statement.
7501   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7502   if (!NBody)
7503     return;
7504 
7505   // Skip expensive checks if diagnostic is disabled.
7506   if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7507           DiagnosticsEngine::Ignored)
7508     return;
7509 
7510   // Do the usual checks.
7511   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7512     return;
7513 
7514   // `for(...);' and `while(...);' are popular idioms, so in order to keep
7515   // noise level low, emit diagnostics only if for/while is followed by a
7516   // CompoundStmt, e.g.:
7517   //    for (int i = 0; i < n; i++);
7518   //    {
7519   //      a(i);
7520   //    }
7521   // or if for/while is followed by a statement with more indentation
7522   // than for/while itself:
7523   //    for (int i = 0; i < n; i++);
7524   //      a(i);
7525   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7526   if (!ProbableTypo) {
7527     bool BodyColInvalid;
7528     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7529                              PossibleBody->getLocStart(),
7530                              &BodyColInvalid);
7531     if (BodyColInvalid)
7532       return;
7533 
7534     bool StmtColInvalid;
7535     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7536                              S->getLocStart(),
7537                              &StmtColInvalid);
7538     if (StmtColInvalid)
7539       return;
7540 
7541     if (BodyCol > StmtCol)
7542       ProbableTypo = true;
7543   }
7544 
7545   if (ProbableTypo) {
7546     Diag(NBody->getSemiLoc(), DiagID);
7547     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7548   }
7549 }
7550 
7551 //===--- Layout compatibility ----------------------------------------------//
7552 
7553 namespace {
7554 
7555 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7556 
7557 /// \brief Check if two enumeration types are layout-compatible.
7558 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7559   // C++11 [dcl.enum] p8:
7560   // Two enumeration types are layout-compatible if they have the same
7561   // underlying type.
7562   return ED1->isComplete() && ED2->isComplete() &&
7563          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7564 }
7565 
7566 /// \brief Check if two fields are layout-compatible.
7567 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7568   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7569     return false;
7570 
7571   if (Field1->isBitField() != Field2->isBitField())
7572     return false;
7573 
7574   if (Field1->isBitField()) {
7575     // Make sure that the bit-fields are the same length.
7576     unsigned Bits1 = Field1->getBitWidthValue(C);
7577     unsigned Bits2 = Field2->getBitWidthValue(C);
7578 
7579     if (Bits1 != Bits2)
7580       return false;
7581   }
7582 
7583   return true;
7584 }
7585 
7586 /// \brief Check if two standard-layout structs are layout-compatible.
7587 /// (C++11 [class.mem] p17)
7588 bool isLayoutCompatibleStruct(ASTContext &C,
7589                               RecordDecl *RD1,
7590                               RecordDecl *RD2) {
7591   // If both records are C++ classes, check that base classes match.
7592   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7593     // If one of records is a CXXRecordDecl we are in C++ mode,
7594     // thus the other one is a CXXRecordDecl, too.
7595     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7596     // Check number of base classes.
7597     if (D1CXX->getNumBases() != D2CXX->getNumBases())
7598       return false;
7599 
7600     // Check the base classes.
7601     for (CXXRecordDecl::base_class_const_iterator
7602                Base1 = D1CXX->bases_begin(),
7603            BaseEnd1 = D1CXX->bases_end(),
7604               Base2 = D2CXX->bases_begin();
7605          Base1 != BaseEnd1;
7606          ++Base1, ++Base2) {
7607       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7608         return false;
7609     }
7610   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7611     // If only RD2 is a C++ class, it should have zero base classes.
7612     if (D2CXX->getNumBases() > 0)
7613       return false;
7614   }
7615 
7616   // Check the fields.
7617   RecordDecl::field_iterator Field2 = RD2->field_begin(),
7618                              Field2End = RD2->field_end(),
7619                              Field1 = RD1->field_begin(),
7620                              Field1End = RD1->field_end();
7621   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7622     if (!isLayoutCompatible(C, *Field1, *Field2))
7623       return false;
7624   }
7625   if (Field1 != Field1End || Field2 != Field2End)
7626     return false;
7627 
7628   return true;
7629 }
7630 
7631 /// \brief Check if two standard-layout unions are layout-compatible.
7632 /// (C++11 [class.mem] p18)
7633 bool isLayoutCompatibleUnion(ASTContext &C,
7634                              RecordDecl *RD1,
7635                              RecordDecl *RD2) {
7636   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7637   for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7638                                   Field2End = RD2->field_end();
7639        Field2 != Field2End; ++Field2) {
7640     UnmatchedFields.insert(*Field2);
7641   }
7642 
7643   for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7644                                   Field1End = RD1->field_end();
7645        Field1 != Field1End; ++Field1) {
7646     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7647         I = UnmatchedFields.begin(),
7648         E = UnmatchedFields.end();
7649 
7650     for ( ; I != E; ++I) {
7651       if (isLayoutCompatible(C, *Field1, *I)) {
7652         bool Result = UnmatchedFields.erase(*I);
7653         (void) Result;
7654         assert(Result);
7655         break;
7656       }
7657     }
7658     if (I == E)
7659       return false;
7660   }
7661 
7662   return UnmatchedFields.empty();
7663 }
7664 
7665 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7666   if (RD1->isUnion() != RD2->isUnion())
7667     return false;
7668 
7669   if (RD1->isUnion())
7670     return isLayoutCompatibleUnion(C, RD1, RD2);
7671   else
7672     return isLayoutCompatibleStruct(C, RD1, RD2);
7673 }
7674 
7675 /// \brief Check if two types are layout-compatible in C++11 sense.
7676 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7677   if (T1.isNull() || T2.isNull())
7678     return false;
7679 
7680   // C++11 [basic.types] p11:
7681   // If two types T1 and T2 are the same type, then T1 and T2 are
7682   // layout-compatible types.
7683   if (C.hasSameType(T1, T2))
7684     return true;
7685 
7686   T1 = T1.getCanonicalType().getUnqualifiedType();
7687   T2 = T2.getCanonicalType().getUnqualifiedType();
7688 
7689   const Type::TypeClass TC1 = T1->getTypeClass();
7690   const Type::TypeClass TC2 = T2->getTypeClass();
7691 
7692   if (TC1 != TC2)
7693     return false;
7694 
7695   if (TC1 == Type::Enum) {
7696     return isLayoutCompatible(C,
7697                               cast<EnumType>(T1)->getDecl(),
7698                               cast<EnumType>(T2)->getDecl());
7699   } else if (TC1 == Type::Record) {
7700     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7701       return false;
7702 
7703     return isLayoutCompatible(C,
7704                               cast<RecordType>(T1)->getDecl(),
7705                               cast<RecordType>(T2)->getDecl());
7706   }
7707 
7708   return false;
7709 }
7710 }
7711 
7712 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7713 
7714 namespace {
7715 /// \brief Given a type tag expression find the type tag itself.
7716 ///
7717 /// \param TypeExpr Type tag expression, as it appears in user's code.
7718 ///
7719 /// \param VD Declaration of an identifier that appears in a type tag.
7720 ///
7721 /// \param MagicValue Type tag magic value.
7722 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7723                      const ValueDecl **VD, uint64_t *MagicValue) {
7724   while(true) {
7725     if (!TypeExpr)
7726       return false;
7727 
7728     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7729 
7730     switch (TypeExpr->getStmtClass()) {
7731     case Stmt::UnaryOperatorClass: {
7732       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7733       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7734         TypeExpr = UO->getSubExpr();
7735         continue;
7736       }
7737       return false;
7738     }
7739 
7740     case Stmt::DeclRefExprClass: {
7741       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7742       *VD = DRE->getDecl();
7743       return true;
7744     }
7745 
7746     case Stmt::IntegerLiteralClass: {
7747       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7748       llvm::APInt MagicValueAPInt = IL->getValue();
7749       if (MagicValueAPInt.getActiveBits() <= 64) {
7750         *MagicValue = MagicValueAPInt.getZExtValue();
7751         return true;
7752       } else
7753         return false;
7754     }
7755 
7756     case Stmt::BinaryConditionalOperatorClass:
7757     case Stmt::ConditionalOperatorClass: {
7758       const AbstractConditionalOperator *ACO =
7759           cast<AbstractConditionalOperator>(TypeExpr);
7760       bool Result;
7761       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7762         if (Result)
7763           TypeExpr = ACO->getTrueExpr();
7764         else
7765           TypeExpr = ACO->getFalseExpr();
7766         continue;
7767       }
7768       return false;
7769     }
7770 
7771     case Stmt::BinaryOperatorClass: {
7772       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7773       if (BO->getOpcode() == BO_Comma) {
7774         TypeExpr = BO->getRHS();
7775         continue;
7776       }
7777       return false;
7778     }
7779 
7780     default:
7781       return false;
7782     }
7783   }
7784 }
7785 
7786 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
7787 ///
7788 /// \param TypeExpr Expression that specifies a type tag.
7789 ///
7790 /// \param MagicValues Registered magic values.
7791 ///
7792 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7793 ///        kind.
7794 ///
7795 /// \param TypeInfo Information about the corresponding C type.
7796 ///
7797 /// \returns true if the corresponding C type was found.
7798 bool GetMatchingCType(
7799         const IdentifierInfo *ArgumentKind,
7800         const Expr *TypeExpr, const ASTContext &Ctx,
7801         const llvm::DenseMap<Sema::TypeTagMagicValue,
7802                              Sema::TypeTagData> *MagicValues,
7803         bool &FoundWrongKind,
7804         Sema::TypeTagData &TypeInfo) {
7805   FoundWrongKind = false;
7806 
7807   // Variable declaration that has type_tag_for_datatype attribute.
7808   const ValueDecl *VD = NULL;
7809 
7810   uint64_t MagicValue;
7811 
7812   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7813     return false;
7814 
7815   if (VD) {
7816     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
7817       if (I->getArgumentKind() != ArgumentKind) {
7818         FoundWrongKind = true;
7819         return false;
7820       }
7821       TypeInfo.Type = I->getMatchingCType();
7822       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7823       TypeInfo.MustBeNull = I->getMustBeNull();
7824       return true;
7825     }
7826     return false;
7827   }
7828 
7829   if (!MagicValues)
7830     return false;
7831 
7832   llvm::DenseMap<Sema::TypeTagMagicValue,
7833                  Sema::TypeTagData>::const_iterator I =
7834       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7835   if (I == MagicValues->end())
7836     return false;
7837 
7838   TypeInfo = I->second;
7839   return true;
7840 }
7841 } // unnamed namespace
7842 
7843 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7844                                       uint64_t MagicValue, QualType Type,
7845                                       bool LayoutCompatible,
7846                                       bool MustBeNull) {
7847   if (!TypeTagForDatatypeMagicValues)
7848     TypeTagForDatatypeMagicValues.reset(
7849         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7850 
7851   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7852   (*TypeTagForDatatypeMagicValues)[Magic] =
7853       TypeTagData(Type, LayoutCompatible, MustBeNull);
7854 }
7855 
7856 namespace {
7857 bool IsSameCharType(QualType T1, QualType T2) {
7858   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7859   if (!BT1)
7860     return false;
7861 
7862   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7863   if (!BT2)
7864     return false;
7865 
7866   BuiltinType::Kind T1Kind = BT1->getKind();
7867   BuiltinType::Kind T2Kind = BT2->getKind();
7868 
7869   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
7870          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
7871          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7872          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7873 }
7874 } // unnamed namespace
7875 
7876 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7877                                     const Expr * const *ExprArgs) {
7878   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7879   bool IsPointerAttr = Attr->getIsPointer();
7880 
7881   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7882   bool FoundWrongKind;
7883   TypeTagData TypeInfo;
7884   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7885                         TypeTagForDatatypeMagicValues.get(),
7886                         FoundWrongKind, TypeInfo)) {
7887     if (FoundWrongKind)
7888       Diag(TypeTagExpr->getExprLoc(),
7889            diag::warn_type_tag_for_datatype_wrong_kind)
7890         << TypeTagExpr->getSourceRange();
7891     return;
7892   }
7893 
7894   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7895   if (IsPointerAttr) {
7896     // Skip implicit cast of pointer to `void *' (as a function argument).
7897     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
7898       if (ICE->getType()->isVoidPointerType() &&
7899           ICE->getCastKind() == CK_BitCast)
7900         ArgumentExpr = ICE->getSubExpr();
7901   }
7902   QualType ArgumentType = ArgumentExpr->getType();
7903 
7904   // Passing a `void*' pointer shouldn't trigger a warning.
7905   if (IsPointerAttr && ArgumentType->isVoidPointerType())
7906     return;
7907 
7908   if (TypeInfo.MustBeNull) {
7909     // Type tag with matching void type requires a null pointer.
7910     if (!ArgumentExpr->isNullPointerConstant(Context,
7911                                              Expr::NPC_ValueDependentIsNotNull)) {
7912       Diag(ArgumentExpr->getExprLoc(),
7913            diag::warn_type_safety_null_pointer_required)
7914           << ArgumentKind->getName()
7915           << ArgumentExpr->getSourceRange()
7916           << TypeTagExpr->getSourceRange();
7917     }
7918     return;
7919   }
7920 
7921   QualType RequiredType = TypeInfo.Type;
7922   if (IsPointerAttr)
7923     RequiredType = Context.getPointerType(RequiredType);
7924 
7925   bool mismatch = false;
7926   if (!TypeInfo.LayoutCompatible) {
7927     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7928 
7929     // C++11 [basic.fundamental] p1:
7930     // Plain char, signed char, and unsigned char are three distinct types.
7931     //
7932     // But we treat plain `char' as equivalent to `signed char' or `unsigned
7933     // char' depending on the current char signedness mode.
7934     if (mismatch)
7935       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7936                                            RequiredType->getPointeeType())) ||
7937           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7938         mismatch = false;
7939   } else
7940     if (IsPointerAttr)
7941       mismatch = !isLayoutCompatible(Context,
7942                                      ArgumentType->getPointeeType(),
7943                                      RequiredType->getPointeeType());
7944     else
7945       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7946 
7947   if (mismatch)
7948     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7949         << ArgumentType << ArgumentKind
7950         << TypeInfo.LayoutCompatible << RequiredType
7951         << ArgumentExpr->getSourceRange()
7952         << TypeTagExpr->getSourceRange();
7953 }
7954 
7955