1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
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 coordinates the per-function state used while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGBlocks.h"
16 #include "CGCleanup.h"
17 #include "CGCUDARuntime.h"
18 #include "CGCXXABI.h"
19 #include "CGDebugInfo.h"
20 #include "CGOpenMPRuntime.h"
21 #include "CodeGenModule.h"
22 #include "CodeGenPGO.h"
23 #include "TargetInfo.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/Decl.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/AST/StmtObjC.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/CodeGen/CGFunctionInfo.h"
32 #include "clang/Frontend/CodeGenOptions.h"
33 #include "clang/Sema/SemaDiagnostic.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/MDBuilder.h"
37 #include "llvm/IR/Operator.h"
38 using namespace clang;
39 using namespace CodeGen;
40 
41 /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
42 /// markers.
43 static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
44                                       const LangOptions &LangOpts) {
45   if (CGOpts.DisableLifetimeMarkers)
46     return false;
47 
48   // Asan uses markers for use-after-scope checks.
49   if (CGOpts.SanitizeAddressUseAfterScope)
50     return true;
51 
52   // Disable lifetime markers in msan builds.
53   // FIXME: Remove this when msan works with lifetime markers.
54   if (LangOpts.Sanitize.has(SanitizerKind::Memory))
55     return false;
56 
57   // For now, only in optimized builds.
58   return CGOpts.OptimizationLevel != 0;
59 }
60 
61 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
62     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
63       Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
64               CGBuilderInserterTy(this)),
65       CurFn(nullptr), ReturnValue(Address::invalid()),
66       CapturedStmtInfo(nullptr), SanOpts(CGM.getLangOpts().Sanitize),
67       IsSanitizerScope(false), CurFuncIsThunk(false), AutoreleaseResult(false),
68       SawAsmBlock(false), IsOutlinedSEHHelper(false), BlockInfo(nullptr),
69       BlockPointer(nullptr), LambdaThisCaptureField(nullptr),
70       NormalCleanupDest(nullptr), NextCleanupDestIndex(1),
71       FirstBlockInfo(nullptr), EHResumeBlock(nullptr), ExceptionSlot(nullptr),
72       EHSelectorSlot(nullptr), DebugInfo(CGM.getModuleDebugInfo()),
73       DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr),
74       PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
75       CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
76       NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
77       CXXABIThisValue(nullptr), CXXThisValue(nullptr),
78       CXXStructorImplicitParamDecl(nullptr),
79       CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
80       CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
81       TerminateHandler(nullptr), TrapBB(nullptr),
82       ShouldEmitLifetimeMarkers(
83           shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
84   if (!suppressNewContext)
85     CGM.getCXXABI().getMangleContext().startNewFunction();
86 
87   llvm::FastMathFlags FMF;
88   if (CGM.getLangOpts().FastMath)
89     FMF.setUnsafeAlgebra();
90   if (CGM.getLangOpts().FiniteMathOnly) {
91     FMF.setNoNaNs();
92     FMF.setNoInfs();
93   }
94   if (CGM.getCodeGenOpts().NoNaNsFPMath) {
95     FMF.setNoNaNs();
96   }
97   if (CGM.getCodeGenOpts().NoSignedZeros) {
98     FMF.setNoSignedZeros();
99   }
100   if (CGM.getCodeGenOpts().ReciprocalMath) {
101     FMF.setAllowReciprocal();
102   }
103   Builder.setFastMathFlags(FMF);
104 }
105 
106 CodeGenFunction::~CodeGenFunction() {
107   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
108 
109   // If there are any unclaimed block infos, go ahead and destroy them
110   // now.  This can happen if IR-gen gets clever and skips evaluating
111   // something.
112   if (FirstBlockInfo)
113     destroyBlockInfos(FirstBlockInfo);
114 
115   if (getLangOpts().OpenMP && CurFn)
116     CGM.getOpenMPRuntime().functionFinished(*this);
117 }
118 
119 CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
120                                                      AlignmentSource *Source) {
121   return getNaturalTypeAlignment(T->getPointeeType(), Source,
122                                  /*forPointee*/ true);
123 }
124 
125 CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
126                                                    AlignmentSource *Source,
127                                                    bool forPointeeType) {
128   // Honor alignment typedef attributes even on incomplete types.
129   // We also honor them straight for C++ class types, even as pointees;
130   // there's an expressivity gap here.
131   if (auto TT = T->getAs<TypedefType>()) {
132     if (auto Align = TT->getDecl()->getMaxAlignment()) {
133       if (Source) *Source = AlignmentSource::AttributedType;
134       return getContext().toCharUnitsFromBits(Align);
135     }
136   }
137 
138   if (Source) *Source = AlignmentSource::Type;
139 
140   CharUnits Alignment;
141   if (T->isIncompleteType()) {
142     Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
143   } else {
144     // For C++ class pointees, we don't know whether we're pointing at a
145     // base or a complete object, so we generally need to use the
146     // non-virtual alignment.
147     const CXXRecordDecl *RD;
148     if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
149       Alignment = CGM.getClassPointerAlignment(RD);
150     } else {
151       Alignment = getContext().getTypeAlignInChars(T);
152     }
153 
154     // Cap to the global maximum type alignment unless the alignment
155     // was somehow explicit on the type.
156     if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
157       if (Alignment.getQuantity() > MaxAlign &&
158           !getContext().isAlignmentRequired(T))
159         Alignment = CharUnits::fromQuantity(MaxAlign);
160     }
161   }
162   return Alignment;
163 }
164 
165 LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
166   AlignmentSource AlignSource;
167   CharUnits Alignment = getNaturalTypeAlignment(T, &AlignSource);
168   return LValue::MakeAddr(Address(V, Alignment), T, getContext(), AlignSource,
169                           CGM.getTBAAInfo(T));
170 }
171 
172 /// Given a value of type T* that may not be to a complete object,
173 /// construct an l-value with the natural pointee alignment of T.
174 LValue
175 CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
176   AlignmentSource AlignSource;
177   CharUnits Align = getNaturalTypeAlignment(T, &AlignSource, /*pointee*/ true);
178   return MakeAddrLValue(Address(V, Align), T, AlignSource);
179 }
180 
181 
182 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
183   return CGM.getTypes().ConvertTypeForMem(T);
184 }
185 
186 llvm::Type *CodeGenFunction::ConvertType(QualType T) {
187   return CGM.getTypes().ConvertType(T);
188 }
189 
190 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
191   type = type.getCanonicalType();
192   while (true) {
193     switch (type->getTypeClass()) {
194 #define TYPE(name, parent)
195 #define ABSTRACT_TYPE(name, parent)
196 #define NON_CANONICAL_TYPE(name, parent) case Type::name:
197 #define DEPENDENT_TYPE(name, parent) case Type::name:
198 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
199 #include "clang/AST/TypeNodes.def"
200       llvm_unreachable("non-canonical or dependent type in IR-generation");
201 
202     case Type::Auto:
203       llvm_unreachable("undeduced auto type in IR-generation");
204 
205     // Various scalar types.
206     case Type::Builtin:
207     case Type::Pointer:
208     case Type::BlockPointer:
209     case Type::LValueReference:
210     case Type::RValueReference:
211     case Type::MemberPointer:
212     case Type::Vector:
213     case Type::ExtVector:
214     case Type::FunctionProto:
215     case Type::FunctionNoProto:
216     case Type::Enum:
217     case Type::ObjCObjectPointer:
218     case Type::Pipe:
219       return TEK_Scalar;
220 
221     // Complexes.
222     case Type::Complex:
223       return TEK_Complex;
224 
225     // Arrays, records, and Objective-C objects.
226     case Type::ConstantArray:
227     case Type::IncompleteArray:
228     case Type::VariableArray:
229     case Type::Record:
230     case Type::ObjCObject:
231     case Type::ObjCInterface:
232       return TEK_Aggregate;
233 
234     // We operate on atomic values according to their underlying type.
235     case Type::Atomic:
236       type = cast<AtomicType>(type)->getValueType();
237       continue;
238     }
239     llvm_unreachable("unknown type kind!");
240   }
241 }
242 
243 llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
244   // For cleanliness, we try to avoid emitting the return block for
245   // simple cases.
246   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
247 
248   if (CurBB) {
249     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
250 
251     // We have a valid insert point, reuse it if it is empty or there are no
252     // explicit jumps to the return block.
253     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
254       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
255       delete ReturnBlock.getBlock();
256     } else
257       EmitBlock(ReturnBlock.getBlock());
258     return llvm::DebugLoc();
259   }
260 
261   // Otherwise, if the return block is the target of a single direct
262   // branch then we can just put the code in that block instead. This
263   // cleans up functions which started with a unified return block.
264   if (ReturnBlock.getBlock()->hasOneUse()) {
265     llvm::BranchInst *BI =
266       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
267     if (BI && BI->isUnconditional() &&
268         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
269       // Record/return the DebugLoc of the simple 'return' expression to be used
270       // later by the actual 'ret' instruction.
271       llvm::DebugLoc Loc = BI->getDebugLoc();
272       Builder.SetInsertPoint(BI->getParent());
273       BI->eraseFromParent();
274       delete ReturnBlock.getBlock();
275       return Loc;
276     }
277   }
278 
279   // FIXME: We are at an unreachable point, there is no reason to emit the block
280   // unless it has uses. However, we still need a place to put the debug
281   // region.end for now.
282 
283   EmitBlock(ReturnBlock.getBlock());
284   return llvm::DebugLoc();
285 }
286 
287 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
288   if (!BB) return;
289   if (!BB->use_empty())
290     return CGF.CurFn->getBasicBlockList().push_back(BB);
291   delete BB;
292 }
293 
294 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
295   assert(BreakContinueStack.empty() &&
296          "mismatched push/pop in break/continue stack!");
297 
298   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
299     && NumSimpleReturnExprs == NumReturnExprs
300     && ReturnBlock.getBlock()->use_empty();
301   // Usually the return expression is evaluated before the cleanup
302   // code.  If the function contains only a simple return statement,
303   // such as a constant, the location before the cleanup code becomes
304   // the last useful breakpoint in the function, because the simple
305   // return expression will be evaluated after the cleanup code. To be
306   // safe, set the debug location for cleanup code to the location of
307   // the return statement.  Otherwise the cleanup code should be at the
308   // end of the function's lexical scope.
309   //
310   // If there are multiple branches to the return block, the branch
311   // instructions will get the location of the return statements and
312   // all will be fine.
313   if (CGDebugInfo *DI = getDebugInfo()) {
314     if (OnlySimpleReturnStmts)
315       DI->EmitLocation(Builder, LastStopPoint);
316     else
317       DI->EmitLocation(Builder, EndLoc);
318   }
319 
320   // Pop any cleanups that might have been associated with the
321   // parameters.  Do this in whatever block we're currently in; it's
322   // important to do this before we enter the return block or return
323   // edges will be *really* confused.
324   bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
325   bool HasOnlyLifetimeMarkers =
326       HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
327   bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
328   if (HasCleanups) {
329     // Make sure the line table doesn't jump back into the body for
330     // the ret after it's been at EndLoc.
331     if (CGDebugInfo *DI = getDebugInfo())
332       if (OnlySimpleReturnStmts)
333         DI->EmitLocation(Builder, EndLoc);
334 
335     PopCleanupBlocks(PrologueCleanupDepth);
336   }
337 
338   // Emit function epilog (to return).
339   llvm::DebugLoc Loc = EmitReturnBlock();
340 
341   if (ShouldInstrumentFunction())
342     EmitFunctionInstrumentation("__cyg_profile_func_exit");
343 
344   // Emit debug descriptor for function end.
345   if (CGDebugInfo *DI = getDebugInfo())
346     DI->EmitFunctionEnd(Builder);
347 
348   // Reset the debug location to that of the simple 'return' expression, if any
349   // rather than that of the end of the function's scope '}'.
350   ApplyDebugLocation AL(*this, Loc);
351   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
352   EmitEndEHSpec(CurCodeDecl);
353 
354   assert(EHStack.empty() &&
355          "did not remove all scopes from cleanup stack!");
356 
357   // If someone did an indirect goto, emit the indirect goto block at the end of
358   // the function.
359   if (IndirectBranch) {
360     EmitBlock(IndirectBranch->getParent());
361     Builder.ClearInsertionPoint();
362   }
363 
364   // If some of our locals escaped, insert a call to llvm.localescape in the
365   // entry block.
366   if (!EscapedLocals.empty()) {
367     // Invert the map from local to index into a simple vector. There should be
368     // no holes.
369     SmallVector<llvm::Value *, 4> EscapeArgs;
370     EscapeArgs.resize(EscapedLocals.size());
371     for (auto &Pair : EscapedLocals)
372       EscapeArgs[Pair.second] = Pair.first;
373     llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
374         &CGM.getModule(), llvm::Intrinsic::localescape);
375     CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
376   }
377 
378   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
379   llvm::Instruction *Ptr = AllocaInsertPt;
380   AllocaInsertPt = nullptr;
381   Ptr->eraseFromParent();
382 
383   // If someone took the address of a label but never did an indirect goto, we
384   // made a zero entry PHI node, which is illegal, zap it now.
385   if (IndirectBranch) {
386     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
387     if (PN->getNumIncomingValues() == 0) {
388       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
389       PN->eraseFromParent();
390     }
391   }
392 
393   EmitIfUsed(*this, EHResumeBlock);
394   EmitIfUsed(*this, TerminateLandingPad);
395   EmitIfUsed(*this, TerminateHandler);
396   EmitIfUsed(*this, UnreachableBlock);
397 
398   if (CGM.getCodeGenOpts().EmitDeclMetadata)
399     EmitDeclMetadata();
400 
401   for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
402            I = DeferredReplacements.begin(),
403            E = DeferredReplacements.end();
404        I != E; ++I) {
405     I->first->replaceAllUsesWith(I->second);
406     I->first->eraseFromParent();
407   }
408 }
409 
410 /// ShouldInstrumentFunction - Return true if the current function should be
411 /// instrumented with __cyg_profile_func_* calls
412 bool CodeGenFunction::ShouldInstrumentFunction() {
413   if (!CGM.getCodeGenOpts().InstrumentFunctions)
414     return false;
415   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
416     return false;
417   return true;
418 }
419 
420 /// ShouldXRayInstrument - Return true if the current function should be
421 /// instrumented with XRay nop sleds.
422 bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
423   return CGM.getCodeGenOpts().XRayInstrumentFunctions;
424 }
425 
426 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
427 /// instrumentation function with the current function and the call site, if
428 /// function instrumentation is enabled.
429 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
430   auto NL = ApplyDebugLocation::CreateArtificial(*this);
431   // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
432   llvm::PointerType *PointerTy = Int8PtrTy;
433   llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
434   llvm::FunctionType *FunctionTy =
435     llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
436 
437   llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
438   llvm::CallInst *CallSite = Builder.CreateCall(
439     CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
440     llvm::ConstantInt::get(Int32Ty, 0),
441     "callsite");
442 
443   llvm::Value *args[] = {
444     llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
445     CallSite
446   };
447 
448   EmitNounwindRuntimeCall(F, args);
449 }
450 
451 static void removeImageAccessQualifier(std::string& TyName) {
452   std::string ReadOnlyQual("__read_only");
453   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
454   if (ReadOnlyPos != std::string::npos)
455     // "+ 1" for the space after access qualifier.
456     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
457   else {
458     std::string WriteOnlyQual("__write_only");
459     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
460     if (WriteOnlyPos != std::string::npos)
461       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
462     else {
463       std::string ReadWriteQual("__read_write");
464       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
465       if (ReadWritePos != std::string::npos)
466         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
467     }
468   }
469 }
470 
471 // Returns the address space id that should be produced to the
472 // kernel_arg_addr_space metadata. This is always fixed to the ids
473 // as specified in the SPIR 2.0 specification in order to differentiate
474 // for example in clGetKernelArgInfo() implementation between the address
475 // spaces with targets without unique mapping to the OpenCL address spaces
476 // (basically all single AS CPUs).
477 static unsigned ArgInfoAddressSpace(unsigned LangAS) {
478   switch (LangAS) {
479   case LangAS::opencl_global:   return 1;
480   case LangAS::opencl_constant: return 2;
481   case LangAS::opencl_local:    return 3;
482   case LangAS::opencl_generic:  return 4; // Not in SPIR 2.0 specs.
483   default:
484     return 0; // Assume private.
485   }
486 }
487 
488 // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
489 // information in the program executable. The argument information stored
490 // includes the argument name, its type, the address and access qualifiers used.
491 static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
492                                  CodeGenModule &CGM, llvm::LLVMContext &Context,
493                                  CGBuilderTy &Builder, ASTContext &ASTCtx) {
494   // Create MDNodes that represent the kernel arg metadata.
495   // Each MDNode is a list in the form of "key", N number of values which is
496   // the same number of values as their are kernel arguments.
497 
498   const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
499 
500   // MDNode for the kernel argument address space qualifiers.
501   SmallVector<llvm::Metadata *, 8> addressQuals;
502 
503   // MDNode for the kernel argument access qualifiers (images only).
504   SmallVector<llvm::Metadata *, 8> accessQuals;
505 
506   // MDNode for the kernel argument type names.
507   SmallVector<llvm::Metadata *, 8> argTypeNames;
508 
509   // MDNode for the kernel argument base type names.
510   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
511 
512   // MDNode for the kernel argument type qualifiers.
513   SmallVector<llvm::Metadata *, 8> argTypeQuals;
514 
515   // MDNode for the kernel argument names.
516   SmallVector<llvm::Metadata *, 8> argNames;
517 
518   for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
519     const ParmVarDecl *parm = FD->getParamDecl(i);
520     QualType ty = parm->getType();
521     std::string typeQuals;
522 
523     if (ty->isPointerType()) {
524       QualType pointeeTy = ty->getPointeeType();
525 
526       // Get address qualifier.
527       addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
528         ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
529 
530       // Get argument type name.
531       std::string typeName =
532           pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
533 
534       // Turn "unsigned type" to "utype"
535       std::string::size_type pos = typeName.find("unsigned");
536       if (pointeeTy.isCanonical() && pos != std::string::npos)
537         typeName.erase(pos+1, 8);
538 
539       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
540 
541       std::string baseTypeName =
542           pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
543               Policy) +
544           "*";
545 
546       // Turn "unsigned type" to "utype"
547       pos = baseTypeName.find("unsigned");
548       if (pos != std::string::npos)
549         baseTypeName.erase(pos+1, 8);
550 
551       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
552 
553       // Get argument type qualifiers:
554       if (ty.isRestrictQualified())
555         typeQuals = "restrict";
556       if (pointeeTy.isConstQualified() ||
557           (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
558         typeQuals += typeQuals.empty() ? "const" : " const";
559       if (pointeeTy.isVolatileQualified())
560         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
561     } else {
562       uint32_t AddrSpc = 0;
563       bool isPipe = ty->isPipeType();
564       if (ty->isImageType() || isPipe)
565         AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
566 
567       addressQuals.push_back(
568           llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
569 
570       // Get argument type name.
571       std::string typeName;
572       if (isPipe)
573         typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType()
574                      .getAsString(Policy);
575       else
576         typeName = ty.getUnqualifiedType().getAsString(Policy);
577 
578       // Turn "unsigned type" to "utype"
579       std::string::size_type pos = typeName.find("unsigned");
580       if (ty.isCanonical() && pos != std::string::npos)
581         typeName.erase(pos+1, 8);
582 
583       std::string baseTypeName;
584       if (isPipe)
585         baseTypeName = ty.getCanonicalType()->getAs<PipeType>()
586                           ->getElementType().getCanonicalType()
587                           .getAsString(Policy);
588       else
589         baseTypeName =
590           ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
591 
592       // Remove access qualifiers on images
593       // (as they are inseparable from type in clang implementation,
594       // but OpenCL spec provides a special query to get access qualifier
595       // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
596       if (ty->isImageType()) {
597         removeImageAccessQualifier(typeName);
598         removeImageAccessQualifier(baseTypeName);
599       }
600 
601       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
602 
603       // Turn "unsigned type" to "utype"
604       pos = baseTypeName.find("unsigned");
605       if (pos != std::string::npos)
606         baseTypeName.erase(pos+1, 8);
607 
608       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
609 
610       // Get argument type qualifiers:
611       if (ty.isConstQualified())
612         typeQuals = "const";
613       if (ty.isVolatileQualified())
614         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
615       if (isPipe)
616         typeQuals = "pipe";
617     }
618 
619     argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
620 
621     // Get image and pipe access qualifier:
622     if (ty->isImageType()|| ty->isPipeType()) {
623       const OpenCLAccessAttr *A = parm->getAttr<OpenCLAccessAttr>();
624       if (A && A->isWriteOnly())
625         accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
626       else if (A && A->isReadWrite())
627         accessQuals.push_back(llvm::MDString::get(Context, "read_write"));
628       else
629         accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
630     } else
631       accessQuals.push_back(llvm::MDString::get(Context, "none"));
632 
633     // Get argument name.
634     argNames.push_back(llvm::MDString::get(Context, parm->getName()));
635   }
636 
637   Fn->setMetadata("kernel_arg_addr_space",
638                   llvm::MDNode::get(Context, addressQuals));
639   Fn->setMetadata("kernel_arg_access_qual",
640                   llvm::MDNode::get(Context, accessQuals));
641   Fn->setMetadata("kernel_arg_type",
642                   llvm::MDNode::get(Context, argTypeNames));
643   Fn->setMetadata("kernel_arg_base_type",
644                   llvm::MDNode::get(Context, argBaseTypeNames));
645   Fn->setMetadata("kernel_arg_type_qual",
646                   llvm::MDNode::get(Context, argTypeQuals));
647   if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
648     Fn->setMetadata("kernel_arg_name",
649                     llvm::MDNode::get(Context, argNames));
650 }
651 
652 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
653                                                llvm::Function *Fn)
654 {
655   if (!FD->hasAttr<OpenCLKernelAttr>())
656     return;
657 
658   llvm::LLVMContext &Context = getLLVMContext();
659 
660   GenOpenCLArgMetadata(FD, Fn, CGM, Context, Builder, getContext());
661 
662   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
663     QualType hintQTy = A->getTypeHint();
664     const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
665     bool isSignedInteger =
666         hintQTy->isSignedIntegerType() ||
667         (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
668     llvm::Metadata *attrMDArgs[] = {
669         llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
670             CGM.getTypes().ConvertType(A->getTypeHint()))),
671         llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
672             llvm::IntegerType::get(Context, 32),
673             llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
674     Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, attrMDArgs));
675   }
676 
677   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
678     llvm::Metadata *attrMDArgs[] = {
679         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
680         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
681         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
682     Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, attrMDArgs));
683   }
684 
685   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
686     llvm::Metadata *attrMDArgs[] = {
687         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
688         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
689         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
690     Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, attrMDArgs));
691   }
692 }
693 
694 /// Determine whether the function F ends with a return stmt.
695 static bool endsWithReturn(const Decl* F) {
696   const Stmt *Body = nullptr;
697   if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
698     Body = FD->getBody();
699   else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
700     Body = OMD->getBody();
701 
702   if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
703     auto LastStmt = CS->body_rbegin();
704     if (LastStmt != CS->body_rend())
705       return isa<ReturnStmt>(*LastStmt);
706   }
707   return false;
708 }
709 
710 static void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
711   Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
712   Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
713 }
714 
715 void CodeGenFunction::StartFunction(GlobalDecl GD,
716                                     QualType RetTy,
717                                     llvm::Function *Fn,
718                                     const CGFunctionInfo &FnInfo,
719                                     const FunctionArgList &Args,
720                                     SourceLocation Loc,
721                                     SourceLocation StartLoc) {
722   assert(!CurFn &&
723          "Do not use a CodeGenFunction object for more than one function");
724 
725   const Decl *D = GD.getDecl();
726 
727   DidCallStackSave = false;
728   CurCodeDecl = D;
729   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
730     if (FD->usesSEHTry())
731       CurSEHParent = FD;
732   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
733   FnRetTy = RetTy;
734   CurFn = Fn;
735   CurFnInfo = &FnInfo;
736   assert(CurFn->isDeclaration() && "Function already has body?");
737 
738   if (CGM.isInSanitizerBlacklist(Fn, Loc))
739     SanOpts.clear();
740 
741   if (D) {
742     // Apply the no_sanitize* attributes to SanOpts.
743     for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
744       SanOpts.Mask &= ~Attr->getMask();
745   }
746 
747   // Apply sanitizer attributes to the function.
748   if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
749     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
750   if (SanOpts.has(SanitizerKind::Thread))
751     Fn->addFnAttr(llvm::Attribute::SanitizeThread);
752   if (SanOpts.has(SanitizerKind::Memory))
753     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
754   if (SanOpts.has(SanitizerKind::SafeStack))
755     Fn->addFnAttr(llvm::Attribute::SafeStack);
756 
757   // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
758   // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
759   if (SanOpts.has(SanitizerKind::Thread)) {
760     if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
761       IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
762       if (OMD->getMethodFamily() == OMF_dealloc ||
763           OMD->getMethodFamily() == OMF_initialize ||
764           (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
765         markAsIgnoreThreadCheckingAtRuntime(Fn);
766       }
767     } else if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
768       IdentifierInfo *II = FD->getIdentifier();
769       if (II && II->isStr("__destroy_helper_block_"))
770         markAsIgnoreThreadCheckingAtRuntime(Fn);
771     }
772   }
773 
774   // Apply xray attributes to the function (as a string, for now)
775   if (D && ShouldXRayInstrumentFunction()) {
776     if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
777       if (XRayAttr->alwaysXRayInstrument())
778         Fn->addFnAttr("function-instrument", "xray-always");
779       if (XRayAttr->neverXRayInstrument())
780         Fn->addFnAttr("function-instrument", "xray-never");
781     } else {
782       Fn->addFnAttr(
783           "xray-instruction-threshold",
784           llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
785     }
786   }
787 
788   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
789     if (CGM.getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
790       CGM.getOpenMPRuntime().emitDeclareSimdFunction(FD, Fn);
791 
792   // Add no-jump-tables value.
793   Fn->addFnAttr("no-jump-tables",
794                 llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
795 
796   if (getLangOpts().OpenCL) {
797     // Add metadata for a kernel function.
798     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
799       EmitOpenCLKernelMetadata(FD, Fn);
800   }
801 
802   // If we are checking function types, emit a function type signature as
803   // prologue data.
804   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
805     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
806       if (llvm::Constant *PrologueSig =
807               CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
808         llvm::Constant *FTRTTIConst =
809             CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
810         llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
811         llvm::Constant *PrologueStructConst =
812             llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
813         Fn->setPrologueData(PrologueStructConst);
814       }
815     }
816   }
817 
818   // If we're in C++ mode and the function name is "main", it is guaranteed
819   // to be norecurse by the standard (3.6.1.3 "The function main shall not be
820   // used within a program").
821   if (getLangOpts().CPlusPlus)
822     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
823       if (FD->isMain())
824         Fn->addFnAttr(llvm::Attribute::NoRecurse);
825 
826   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
827 
828   // Create a marker to make it easy to insert allocas into the entryblock
829   // later.  Don't create this with the builder, because we don't want it
830   // folded.
831   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
832   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
833 
834   ReturnBlock = getJumpDestInCurrentScope("return");
835 
836   Builder.SetInsertPoint(EntryBB);
837 
838   // Emit subprogram debug descriptor.
839   if (CGDebugInfo *DI = getDebugInfo()) {
840     // Reconstruct the type from the argument list so that implicit parameters,
841     // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
842     // convention.
843     CallingConv CC = CallingConv::CC_C;
844     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
845       if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
846         CC = SrcFnTy->getCallConv();
847     SmallVector<QualType, 16> ArgTypes;
848     for (const VarDecl *VD : Args)
849       ArgTypes.push_back(VD->getType());
850     QualType FnType = getContext().getFunctionType(
851         RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
852     DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
853   }
854 
855   if (ShouldInstrumentFunction())
856     EmitFunctionInstrumentation("__cyg_profile_func_enter");
857 
858   // Since emitting the mcount call here impacts optimizations such as function
859   // inlining, we just add an attribute to insert a mcount call in backend.
860   // The attribute "counting-function" is set to mcount function name which is
861   // architecture dependent.
862   if (CGM.getCodeGenOpts().InstrumentForProfiling)
863     Fn->addFnAttr("counting-function", getTarget().getMCountName());
864 
865   if (RetTy->isVoidType()) {
866     // Void type; nothing to return.
867     ReturnValue = Address::invalid();
868 
869     // Count the implicit return.
870     if (!endsWithReturn(D))
871       ++NumReturnExprs;
872   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
873              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
874     // Indirect aggregate return; emit returned value directly into sret slot.
875     // This reduces code size, and affects correctness in C++.
876     auto AI = CurFn->arg_begin();
877     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
878       ++AI;
879     ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
880   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
881              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
882     // Load the sret pointer from the argument struct and return into that.
883     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
884     llvm::Function::arg_iterator EI = CurFn->arg_end();
885     --EI;
886     llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
887     Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
888     ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
889   } else {
890     ReturnValue = CreateIRTemp(RetTy, "retval");
891 
892     // Tell the epilog emitter to autorelease the result.  We do this
893     // now so that various specialized functions can suppress it
894     // during their IR-generation.
895     if (getLangOpts().ObjCAutoRefCount &&
896         !CurFnInfo->isReturnsRetained() &&
897         RetTy->isObjCRetainableType())
898       AutoreleaseResult = true;
899   }
900 
901   EmitStartEHSpec(CurCodeDecl);
902 
903   PrologueCleanupDepth = EHStack.stable_begin();
904   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
905 
906   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
907     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
908     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
909     if (MD->getParent()->isLambda() &&
910         MD->getOverloadedOperator() == OO_Call) {
911       // We're in a lambda; figure out the captures.
912       MD->getParent()->getCaptureFields(LambdaCaptureFields,
913                                         LambdaThisCaptureField);
914       if (LambdaThisCaptureField) {
915         // If the lambda captures the object referred to by '*this' - either by
916         // value or by reference, make sure CXXThisValue points to the correct
917         // object.
918 
919         // Get the lvalue for the field (which is a copy of the enclosing object
920         // or contains the address of the enclosing object).
921         LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
922         if (!LambdaThisCaptureField->getType()->isPointerType()) {
923           // If the enclosing object was captured by value, just use its address.
924           CXXThisValue = ThisFieldLValue.getAddress().getPointer();
925         } else {
926           // Load the lvalue pointed to by the field, since '*this' was captured
927           // by reference.
928           CXXThisValue =
929               EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
930         }
931       }
932       for (auto *FD : MD->getParent()->fields()) {
933         if (FD->hasCapturedVLAType()) {
934           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
935                                            SourceLocation()).getScalarVal();
936           auto VAT = FD->getCapturedVLAType();
937           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
938         }
939       }
940     } else {
941       // Not in a lambda; just use 'this' from the method.
942       // FIXME: Should we generate a new load for each use of 'this'?  The
943       // fast register allocator would be happier...
944       CXXThisValue = CXXABIThisValue;
945     }
946   }
947 
948   // If any of the arguments have a variably modified type, make sure to
949   // emit the type size.
950   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
951        i != e; ++i) {
952     const VarDecl *VD = *i;
953 
954     // Dig out the type as written from ParmVarDecls; it's unclear whether
955     // the standard (C99 6.9.1p10) requires this, but we're following the
956     // precedent set by gcc.
957     QualType Ty;
958     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
959       Ty = PVD->getOriginalType();
960     else
961       Ty = VD->getType();
962 
963     if (Ty->isVariablyModifiedType())
964       EmitVariablyModifiedType(Ty);
965   }
966   // Emit a location at the end of the prologue.
967   if (CGDebugInfo *DI = getDebugInfo())
968     DI->EmitLocation(Builder, StartLoc);
969 }
970 
971 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
972                                        const Stmt *Body) {
973   incrementProfileCounter(Body);
974   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
975     EmitCompoundStmtWithoutScope(*S);
976   else
977     EmitStmt(Body);
978 }
979 
980 /// When instrumenting to collect profile data, the counts for some blocks
981 /// such as switch cases need to not include the fall-through counts, so
982 /// emit a branch around the instrumentation code. When not instrumenting,
983 /// this just calls EmitBlock().
984 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
985                                                const Stmt *S) {
986   llvm::BasicBlock *SkipCountBB = nullptr;
987   if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
988     // When instrumenting for profiling, the fallthrough to certain
989     // statements needs to skip over the instrumentation code so that we
990     // get an accurate count.
991     SkipCountBB = createBasicBlock("skipcount");
992     EmitBranch(SkipCountBB);
993   }
994   EmitBlock(BB);
995   uint64_t CurrentCount = getCurrentProfileCount();
996   incrementProfileCounter(S);
997   setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
998   if (SkipCountBB)
999     EmitBlock(SkipCountBB);
1000 }
1001 
1002 /// Tries to mark the given function nounwind based on the
1003 /// non-existence of any throwing calls within it.  We believe this is
1004 /// lightweight enough to do at -O0.
1005 static void TryMarkNoThrow(llvm::Function *F) {
1006   // LLVM treats 'nounwind' on a function as part of the type, so we
1007   // can't do this on functions that can be overwritten.
1008   if (F->isInterposable()) return;
1009 
1010   for (llvm::BasicBlock &BB : *F)
1011     for (llvm::Instruction &I : BB)
1012       if (I.mayThrow())
1013         return;
1014 
1015   F->setDoesNotThrow();
1016 }
1017 
1018 QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1019                                                FunctionArgList &Args) {
1020   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1021   QualType ResTy = FD->getReturnType();
1022 
1023   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1024   if (MD && MD->isInstance()) {
1025     if (CGM.getCXXABI().HasThisReturn(GD))
1026       ResTy = MD->getThisType(getContext());
1027     else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1028       ResTy = CGM.getContext().VoidPtrTy;
1029     CGM.getCXXABI().buildThisParam(*this, Args);
1030   }
1031 
1032   // The base version of an inheriting constructor whose constructed base is a
1033   // virtual base is not passed any arguments (because it doesn't actually call
1034   // the inherited constructor).
1035   bool PassedParams = true;
1036   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1037     if (auto Inherited = CD->getInheritedConstructor())
1038       PassedParams =
1039           getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1040 
1041   if (PassedParams) {
1042     for (auto *Param : FD->parameters()) {
1043       Args.push_back(Param);
1044       if (!Param->hasAttr<PassObjectSizeAttr>())
1045         continue;
1046 
1047       IdentifierInfo *NoID = nullptr;
1048       auto *Implicit = ImplicitParamDecl::Create(
1049           getContext(), Param->getDeclContext(), Param->getLocation(), NoID,
1050           getContext().getSizeType());
1051       SizeArguments[Param] = Implicit;
1052       Args.push_back(Implicit);
1053     }
1054   }
1055 
1056   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1057     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1058 
1059   return ResTy;
1060 }
1061 
1062 static bool
1063 shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
1064                                              const ASTContext &Context) {
1065   QualType T = FD->getReturnType();
1066   // Avoid the optimization for functions that return a record type with a
1067   // trivial destructor or another trivially copyable type.
1068   if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
1069     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1070       return !ClassDecl->hasTrivialDestructor();
1071   }
1072   return !T.isTriviallyCopyableType(Context);
1073 }
1074 
1075 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1076                                    const CGFunctionInfo &FnInfo) {
1077   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1078   CurGD = GD;
1079 
1080   FunctionArgList Args;
1081   QualType ResTy = BuildFunctionArgList(GD, Args);
1082 
1083   // Check if we should generate debug info for this function.
1084   if (FD->hasAttr<NoDebugAttr>())
1085     DebugInfo = nullptr; // disable debug info indefinitely for this function
1086 
1087   SourceRange BodyRange;
1088   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
1089   CurEHLocation = BodyRange.getEnd();
1090 
1091   // Use the location of the start of the function to determine where
1092   // the function definition is located. By default use the location
1093   // of the declaration as the location for the subprogram. A function
1094   // may lack a declaration in the source code if it is created by code
1095   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1096   SourceLocation Loc = FD->getLocation();
1097 
1098   // If this is a function specialization then use the pattern body
1099   // as the location for the function.
1100   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1101     if (SpecDecl->hasBody(SpecDecl))
1102       Loc = SpecDecl->getLocation();
1103 
1104   Stmt *Body = FD->getBody();
1105 
1106   // Initialize helper which will detect jumps which can cause invalid lifetime
1107   // markers.
1108   if (Body && ShouldEmitLifetimeMarkers)
1109     Bypasses.Init(Body);
1110 
1111   // Emit the standard function prologue.
1112   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1113 
1114   // Generate the body of the function.
1115   PGO.assignRegionCounters(GD, CurFn);
1116   if (isa<CXXDestructorDecl>(FD))
1117     EmitDestructorBody(Args);
1118   else if (isa<CXXConstructorDecl>(FD))
1119     EmitConstructorBody(Args);
1120   else if (getLangOpts().CUDA &&
1121            !getLangOpts().CUDAIsDevice &&
1122            FD->hasAttr<CUDAGlobalAttr>())
1123     CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1124   else if (isa<CXXConversionDecl>(FD) &&
1125            cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
1126     // The lambda conversion to block pointer is special; the semantics can't be
1127     // expressed in the AST, so IRGen needs to special-case it.
1128     EmitLambdaToBlockPointerBody(Args);
1129   } else if (isa<CXXMethodDecl>(FD) &&
1130              cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1131     // The lambda static invoker function is special, because it forwards or
1132     // clones the body of the function call operator (but is actually static).
1133     EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
1134   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1135              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1136               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1137     // Implicit copy-assignment gets the same special treatment as implicit
1138     // copy-constructors.
1139     emitImplicitAssignmentOperatorBody(Args);
1140   } else if (Body) {
1141     EmitFunctionBody(Args, Body);
1142   } else
1143     llvm_unreachable("no definition for emitted function");
1144 
1145   // C++11 [stmt.return]p2:
1146   //   Flowing off the end of a function [...] results in undefined behavior in
1147   //   a value-returning function.
1148   // C11 6.9.1p12:
1149   //   If the '}' that terminates a function is reached, and the value of the
1150   //   function call is used by the caller, the behavior is undefined.
1151   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
1152       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1153     bool ShouldEmitUnreachable =
1154         CGM.getCodeGenOpts().StrictReturn ||
1155         shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
1156     if (SanOpts.has(SanitizerKind::Return)) {
1157       SanitizerScope SanScope(this);
1158       llvm::Value *IsFalse = Builder.getFalse();
1159       EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1160                 SanitizerHandler::MissingReturn,
1161                 EmitCheckSourceLocation(FD->getLocation()), None);
1162     } else if (ShouldEmitUnreachable) {
1163       if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1164         EmitTrapCall(llvm::Intrinsic::trap);
1165     }
1166     if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1167       Builder.CreateUnreachable();
1168       Builder.ClearInsertionPoint();
1169     }
1170   }
1171 
1172   // Emit the standard function epilogue.
1173   FinishFunction(BodyRange.getEnd());
1174 
1175   // If we haven't marked the function nothrow through other means, do
1176   // a quick pass now to see if we can.
1177   if (!CurFn->doesNotThrow())
1178     TryMarkNoThrow(CurFn);
1179 }
1180 
1181 /// ContainsLabel - Return true if the statement contains a label in it.  If
1182 /// this statement is not executed normally, it not containing a label means
1183 /// that we can just remove the code.
1184 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1185   // Null statement, not a label!
1186   if (!S) return false;
1187 
1188   // If this is a label, we have to emit the code, consider something like:
1189   // if (0) {  ...  foo:  bar(); }  goto foo;
1190   //
1191   // TODO: If anyone cared, we could track __label__'s, since we know that you
1192   // can't jump to one from outside their declared region.
1193   if (isa<LabelStmt>(S))
1194     return true;
1195 
1196   // If this is a case/default statement, and we haven't seen a switch, we have
1197   // to emit the code.
1198   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1199     return true;
1200 
1201   // If this is a switch statement, we want to ignore cases below it.
1202   if (isa<SwitchStmt>(S))
1203     IgnoreCaseStmts = true;
1204 
1205   // Scan subexpressions for verboten labels.
1206   for (const Stmt *SubStmt : S->children())
1207     if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1208       return true;
1209 
1210   return false;
1211 }
1212 
1213 /// containsBreak - Return true if the statement contains a break out of it.
1214 /// If the statement (recursively) contains a switch or loop with a break
1215 /// inside of it, this is fine.
1216 bool CodeGenFunction::containsBreak(const Stmt *S) {
1217   // Null statement, not a label!
1218   if (!S) return false;
1219 
1220   // If this is a switch or loop that defines its own break scope, then we can
1221   // include it and anything inside of it.
1222   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1223       isa<ForStmt>(S))
1224     return false;
1225 
1226   if (isa<BreakStmt>(S))
1227     return true;
1228 
1229   // Scan subexpressions for verboten breaks.
1230   for (const Stmt *SubStmt : S->children())
1231     if (containsBreak(SubStmt))
1232       return true;
1233 
1234   return false;
1235 }
1236 
1237 bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1238   if (!S) return false;
1239 
1240   // Some statement kinds add a scope and thus never add a decl to the current
1241   // scope. Note, this list is longer than the list of statements that might
1242   // have an unscoped decl nested within them, but this way is conservatively
1243   // correct even if more statement kinds are added.
1244   if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1245       isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1246       isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1247       isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1248     return false;
1249 
1250   if (isa<DeclStmt>(S))
1251     return true;
1252 
1253   for (const Stmt *SubStmt : S->children())
1254     if (mightAddDeclToScope(SubStmt))
1255       return true;
1256 
1257   return false;
1258 }
1259 
1260 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1261 /// to a constant, or if it does but contains a label, return false.  If it
1262 /// constant folds return true and set the boolean result in Result.
1263 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1264                                                    bool &ResultBool,
1265                                                    bool AllowLabels) {
1266   llvm::APSInt ResultInt;
1267   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1268     return false;
1269 
1270   ResultBool = ResultInt.getBoolValue();
1271   return true;
1272 }
1273 
1274 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1275 /// to a constant, or if it does but contains a label, return false.  If it
1276 /// constant folds return true and set the folded value.
1277 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1278                                                    llvm::APSInt &ResultInt,
1279                                                    bool AllowLabels) {
1280   // FIXME: Rename and handle conversion of other evaluatable things
1281   // to bool.
1282   llvm::APSInt Int;
1283   if (!Cond->EvaluateAsInt(Int, getContext()))
1284     return false;  // Not foldable, not integer or not fully evaluatable.
1285 
1286   if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
1287     return false;  // Contains a label.
1288 
1289   ResultInt = Int;
1290   return true;
1291 }
1292 
1293 
1294 
1295 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1296 /// statement) to the specified blocks.  Based on the condition, this might try
1297 /// to simplify the codegen of the conditional based on the branch.
1298 ///
1299 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1300                                            llvm::BasicBlock *TrueBlock,
1301                                            llvm::BasicBlock *FalseBlock,
1302                                            uint64_t TrueCount) {
1303   Cond = Cond->IgnoreParens();
1304 
1305   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1306 
1307     // Handle X && Y in a condition.
1308     if (CondBOp->getOpcode() == BO_LAnd) {
1309       // If we have "1 && X", simplify the code.  "0 && X" would have constant
1310       // folded if the case was simple enough.
1311       bool ConstantBool = false;
1312       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1313           ConstantBool) {
1314         // br(1 && X) -> br(X).
1315         incrementProfileCounter(CondBOp);
1316         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1317                                     TrueCount);
1318       }
1319 
1320       // If we have "X && 1", simplify the code to use an uncond branch.
1321       // "X && 0" would have been constant folded to 0.
1322       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1323           ConstantBool) {
1324         // br(X && 1) -> br(X).
1325         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1326                                     TrueCount);
1327       }
1328 
1329       // Emit the LHS as a conditional.  If the LHS conditional is false, we
1330       // want to jump to the FalseBlock.
1331       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1332       // The counter tells us how often we evaluate RHS, and all of TrueCount
1333       // can be propagated to that branch.
1334       uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1335 
1336       ConditionalEvaluation eval(*this);
1337       {
1338         ApplyDebugLocation DL(*this, Cond);
1339         EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1340         EmitBlock(LHSTrue);
1341       }
1342 
1343       incrementProfileCounter(CondBOp);
1344       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1345 
1346       // Any temporaries created here are conditional.
1347       eval.begin(*this);
1348       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
1349       eval.end(*this);
1350 
1351       return;
1352     }
1353 
1354     if (CondBOp->getOpcode() == BO_LOr) {
1355       // If we have "0 || X", simplify the code.  "1 || X" would have constant
1356       // folded if the case was simple enough.
1357       bool ConstantBool = false;
1358       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1359           !ConstantBool) {
1360         // br(0 || X) -> br(X).
1361         incrementProfileCounter(CondBOp);
1362         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1363                                     TrueCount);
1364       }
1365 
1366       // If we have "X || 0", simplify the code to use an uncond branch.
1367       // "X || 1" would have been constant folded to 1.
1368       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1369           !ConstantBool) {
1370         // br(X || 0) -> br(X).
1371         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1372                                     TrueCount);
1373       }
1374 
1375       // Emit the LHS as a conditional.  If the LHS conditional is true, we
1376       // want to jump to the TrueBlock.
1377       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1378       // We have the count for entry to the RHS and for the whole expression
1379       // being true, so we can divy up True count between the short circuit and
1380       // the RHS.
1381       uint64_t LHSCount =
1382           getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1383       uint64_t RHSCount = TrueCount - LHSCount;
1384 
1385       ConditionalEvaluation eval(*this);
1386       {
1387         ApplyDebugLocation DL(*this, Cond);
1388         EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1389         EmitBlock(LHSFalse);
1390       }
1391 
1392       incrementProfileCounter(CondBOp);
1393       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1394 
1395       // Any temporaries created here are conditional.
1396       eval.begin(*this);
1397       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
1398 
1399       eval.end(*this);
1400 
1401       return;
1402     }
1403   }
1404 
1405   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1406     // br(!x, t, f) -> br(x, f, t)
1407     if (CondUOp->getOpcode() == UO_LNot) {
1408       // Negate the count.
1409       uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1410       // Negate the condition and swap the destination blocks.
1411       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1412                                   FalseCount);
1413     }
1414   }
1415 
1416   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1417     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1418     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1419     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1420 
1421     ConditionalEvaluation cond(*this);
1422     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1423                          getProfileCount(CondOp));
1424 
1425     // When computing PGO branch weights, we only know the overall count for
1426     // the true block. This code is essentially doing tail duplication of the
1427     // naive code-gen, introducing new edges for which counts are not
1428     // available. Divide the counts proportionally between the LHS and RHS of
1429     // the conditional operator.
1430     uint64_t LHSScaledTrueCount = 0;
1431     if (TrueCount) {
1432       double LHSRatio =
1433           getProfileCount(CondOp) / (double)getCurrentProfileCount();
1434       LHSScaledTrueCount = TrueCount * LHSRatio;
1435     }
1436 
1437     cond.begin(*this);
1438     EmitBlock(LHSBlock);
1439     incrementProfileCounter(CondOp);
1440     {
1441       ApplyDebugLocation DL(*this, Cond);
1442       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1443                            LHSScaledTrueCount);
1444     }
1445     cond.end(*this);
1446 
1447     cond.begin(*this);
1448     EmitBlock(RHSBlock);
1449     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1450                          TrueCount - LHSScaledTrueCount);
1451     cond.end(*this);
1452 
1453     return;
1454   }
1455 
1456   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1457     // Conditional operator handling can give us a throw expression as a
1458     // condition for a case like:
1459     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1460     // Fold this to:
1461     //   br(c, throw x, br(y, t, f))
1462     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1463     return;
1464   }
1465 
1466   // If the branch has a condition wrapped by __builtin_unpredictable,
1467   // create metadata that specifies that the branch is unpredictable.
1468   // Don't bother if not optimizing because that metadata would not be used.
1469   llvm::MDNode *Unpredictable = nullptr;
1470   auto *Call = dyn_cast<CallExpr>(Cond);
1471   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1472     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1473     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1474       llvm::MDBuilder MDHelper(getLLVMContext());
1475       Unpredictable = MDHelper.createUnpredictable();
1476     }
1477   }
1478 
1479   // Create branch weights based on the number of times we get here and the
1480   // number of times the condition should be true.
1481   uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
1482   llvm::MDNode *Weights =
1483       createProfileWeights(TrueCount, CurrentCount - TrueCount);
1484 
1485   // Emit the code with the fully general case.
1486   llvm::Value *CondV;
1487   {
1488     ApplyDebugLocation DL(*this, Cond);
1489     CondV = EvaluateExprAsBool(Cond);
1490   }
1491   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1492 }
1493 
1494 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1495 /// specified stmt yet.
1496 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1497   CGM.ErrorUnsupported(S, Type);
1498 }
1499 
1500 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
1501 /// variable-length array whose elements have a non-zero bit-pattern.
1502 ///
1503 /// \param baseType the inner-most element type of the array
1504 /// \param src - a char* pointing to the bit-pattern for a single
1505 /// base element of the array
1506 /// \param sizeInChars - the total size of the VLA, in chars
1507 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1508                                Address dest, Address src,
1509                                llvm::Value *sizeInChars) {
1510   CGBuilderTy &Builder = CGF.Builder;
1511 
1512   CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
1513   llvm::Value *baseSizeInChars
1514     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
1515 
1516   Address begin =
1517     Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
1518   llvm::Value *end =
1519     Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
1520 
1521   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1522   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1523   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1524 
1525   // Make a loop over the VLA.  C99 guarantees that the VLA element
1526   // count must be nonzero.
1527   CGF.EmitBlock(loopBB);
1528 
1529   llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
1530   cur->addIncoming(begin.getPointer(), originBB);
1531 
1532   CharUnits curAlign =
1533     dest.getAlignment().alignmentOfArrayElement(baseSize);
1534 
1535   // memcpy the individual element bit-pattern.
1536   Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
1537                        /*volatile*/ false);
1538 
1539   // Go to the next element.
1540   llvm::Value *next =
1541     Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
1542 
1543   // Leave if that's the end of the VLA.
1544   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1545   Builder.CreateCondBr(done, contBB, loopBB);
1546   cur->addIncoming(next, loopBB);
1547 
1548   CGF.EmitBlock(contBB);
1549 }
1550 
1551 void
1552 CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1553   // Ignore empty classes in C++.
1554   if (getLangOpts().CPlusPlus) {
1555     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1556       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1557         return;
1558     }
1559   }
1560 
1561   // Cast the dest ptr to the appropriate i8 pointer type.
1562   if (DestPtr.getElementType() != Int8Ty)
1563     DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1564 
1565   // Get size and alignment info for this aggregate.
1566   CharUnits size = getContext().getTypeSizeInChars(Ty);
1567 
1568   llvm::Value *SizeVal;
1569   const VariableArrayType *vla;
1570 
1571   // Don't bother emitting a zero-byte memset.
1572   if (size.isZero()) {
1573     // But note that getTypeInfo returns 0 for a VLA.
1574     if (const VariableArrayType *vlaType =
1575           dyn_cast_or_null<VariableArrayType>(
1576                                           getContext().getAsArrayType(Ty))) {
1577       QualType eltType;
1578       llvm::Value *numElts;
1579       std::tie(numElts, eltType) = getVLASize(vlaType);
1580 
1581       SizeVal = numElts;
1582       CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
1583       if (!eltSize.isOne())
1584         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1585       vla = vlaType;
1586     } else {
1587       return;
1588     }
1589   } else {
1590     SizeVal = CGM.getSize(size);
1591     vla = nullptr;
1592   }
1593 
1594   // If the type contains a pointer to data member we can't memset it to zero.
1595   // Instead, create a null constant and copy it to the destination.
1596   // TODO: there are other patterns besides zero that we can usefully memset,
1597   // like -1, which happens to be the pattern used by member-pointers.
1598   if (!CGM.getTypes().isZeroInitializable(Ty)) {
1599     // For a VLA, emit a single element, then splat that over the VLA.
1600     if (vla) Ty = getContext().getBaseElementType(vla);
1601 
1602     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1603 
1604     llvm::GlobalVariable *NullVariable =
1605       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1606                                /*isConstant=*/true,
1607                                llvm::GlobalVariable::PrivateLinkage,
1608                                NullConstant, Twine());
1609     CharUnits NullAlign = DestPtr.getAlignment();
1610     NullVariable->setAlignment(NullAlign.getQuantity());
1611     Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
1612                    NullAlign);
1613 
1614     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1615 
1616     // Get and call the appropriate llvm.memcpy overload.
1617     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
1618     return;
1619   }
1620 
1621   // Otherwise, just memset the whole thing to zero.  This is legal
1622   // because in LLVM, all default initializers (other than the ones we just
1623   // handled above) are guaranteed to have a bit pattern of all zeros.
1624   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
1625 }
1626 
1627 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1628   // Make sure that there is a block for the indirect goto.
1629   if (!IndirectBranch)
1630     GetIndirectGotoBlock();
1631 
1632   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1633 
1634   // Make sure the indirect branch includes all of the address-taken blocks.
1635   IndirectBranch->addDestination(BB);
1636   return llvm::BlockAddress::get(CurFn, BB);
1637 }
1638 
1639 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1640   // If we already made the indirect branch for indirect goto, return its block.
1641   if (IndirectBranch) return IndirectBranch->getParent();
1642 
1643   CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
1644 
1645   // Create the PHI node that indirect gotos will add entries to.
1646   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1647                                               "indirect.goto.dest");
1648 
1649   // Create the indirect branch instruction.
1650   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1651   return IndirectBranch->getParent();
1652 }
1653 
1654 /// Computes the length of an array in elements, as well as the base
1655 /// element type and a properly-typed first element pointer.
1656 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
1657                                               QualType &baseType,
1658                                               Address &addr) {
1659   const ArrayType *arrayType = origArrayType;
1660 
1661   // If it's a VLA, we have to load the stored size.  Note that
1662   // this is the size of the VLA in bytes, not its size in elements.
1663   llvm::Value *numVLAElements = nullptr;
1664   if (isa<VariableArrayType>(arrayType)) {
1665     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
1666 
1667     // Walk into all VLAs.  This doesn't require changes to addr,
1668     // which has type T* where T is the first non-VLA element type.
1669     do {
1670       QualType elementType = arrayType->getElementType();
1671       arrayType = getContext().getAsArrayType(elementType);
1672 
1673       // If we only have VLA components, 'addr' requires no adjustment.
1674       if (!arrayType) {
1675         baseType = elementType;
1676         return numVLAElements;
1677       }
1678     } while (isa<VariableArrayType>(arrayType));
1679 
1680     // We get out here only if we find a constant array type
1681     // inside the VLA.
1682   }
1683 
1684   // We have some number of constant-length arrays, so addr should
1685   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
1686   // down to the first element of addr.
1687   SmallVector<llvm::Value*, 8> gepIndices;
1688 
1689   // GEP down to the array type.
1690   llvm::ConstantInt *zero = Builder.getInt32(0);
1691   gepIndices.push_back(zero);
1692 
1693   uint64_t countFromCLAs = 1;
1694   QualType eltType;
1695 
1696   llvm::ArrayType *llvmArrayType =
1697     dyn_cast<llvm::ArrayType>(addr.getElementType());
1698   while (llvmArrayType) {
1699     assert(isa<ConstantArrayType>(arrayType));
1700     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1701              == llvmArrayType->getNumElements());
1702 
1703     gepIndices.push_back(zero);
1704     countFromCLAs *= llvmArrayType->getNumElements();
1705     eltType = arrayType->getElementType();
1706 
1707     llvmArrayType =
1708       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1709     arrayType = getContext().getAsArrayType(arrayType->getElementType());
1710     assert((!llvmArrayType || arrayType) &&
1711            "LLVM and Clang types are out-of-synch");
1712   }
1713 
1714   if (arrayType) {
1715     // From this point onwards, the Clang array type has been emitted
1716     // as some other type (probably a packed struct). Compute the array
1717     // size, and just emit the 'begin' expression as a bitcast.
1718     while (arrayType) {
1719       countFromCLAs *=
1720           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1721       eltType = arrayType->getElementType();
1722       arrayType = getContext().getAsArrayType(eltType);
1723     }
1724 
1725     llvm::Type *baseType = ConvertType(eltType);
1726     addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
1727   } else {
1728     // Create the actual GEP.
1729     addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
1730                                              gepIndices, "array.begin"),
1731                    addr.getAlignment());
1732   }
1733 
1734   baseType = eltType;
1735 
1736   llvm::Value *numElements
1737     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
1738 
1739   // If we had any VLA dimensions, factor them in.
1740   if (numVLAElements)
1741     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
1742 
1743   return numElements;
1744 }
1745 
1746 std::pair<llvm::Value*, QualType>
1747 CodeGenFunction::getVLASize(QualType type) {
1748   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
1749   assert(vla && "type was not a variable array type!");
1750   return getVLASize(vla);
1751 }
1752 
1753 std::pair<llvm::Value*, QualType>
1754 CodeGenFunction::getVLASize(const VariableArrayType *type) {
1755   // The number of elements so far; always size_t.
1756   llvm::Value *numElements = nullptr;
1757 
1758   QualType elementType;
1759   do {
1760     elementType = type->getElementType();
1761     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
1762     assert(vlaSize && "no size for VLA!");
1763     assert(vlaSize->getType() == SizeTy);
1764 
1765     if (!numElements) {
1766       numElements = vlaSize;
1767     } else {
1768       // It's undefined behavior if this wraps around, so mark it that way.
1769       // FIXME: Teach -fsanitize=undefined to trap this.
1770       numElements = Builder.CreateNUWMul(numElements, vlaSize);
1771     }
1772   } while ((type = getContext().getAsVariableArrayType(elementType)));
1773 
1774   return std::pair<llvm::Value*,QualType>(numElements, elementType);
1775 }
1776 
1777 void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
1778   assert(type->isVariablyModifiedType() &&
1779          "Must pass variably modified type to EmitVLASizes!");
1780 
1781   EnsureInsertPoint();
1782 
1783   // We're going to walk down into the type and look for VLA
1784   // expressions.
1785   do {
1786     assert(type->isVariablyModifiedType());
1787 
1788     const Type *ty = type.getTypePtr();
1789     switch (ty->getTypeClass()) {
1790 
1791 #define TYPE(Class, Base)
1792 #define ABSTRACT_TYPE(Class, Base)
1793 #define NON_CANONICAL_TYPE(Class, Base)
1794 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1795 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1796 #include "clang/AST/TypeNodes.def"
1797       llvm_unreachable("unexpected dependent type!");
1798 
1799     // These types are never variably-modified.
1800     case Type::Builtin:
1801     case Type::Complex:
1802     case Type::Vector:
1803     case Type::ExtVector:
1804     case Type::Record:
1805     case Type::Enum:
1806     case Type::Elaborated:
1807     case Type::TemplateSpecialization:
1808     case Type::ObjCTypeParam:
1809     case Type::ObjCObject:
1810     case Type::ObjCInterface:
1811     case Type::ObjCObjectPointer:
1812       llvm_unreachable("type class is never variably-modified!");
1813 
1814     case Type::Adjusted:
1815       type = cast<AdjustedType>(ty)->getAdjustedType();
1816       break;
1817 
1818     case Type::Decayed:
1819       type = cast<DecayedType>(ty)->getPointeeType();
1820       break;
1821 
1822     case Type::Pointer:
1823       type = cast<PointerType>(ty)->getPointeeType();
1824       break;
1825 
1826     case Type::BlockPointer:
1827       type = cast<BlockPointerType>(ty)->getPointeeType();
1828       break;
1829 
1830     case Type::LValueReference:
1831     case Type::RValueReference:
1832       type = cast<ReferenceType>(ty)->getPointeeType();
1833       break;
1834 
1835     case Type::MemberPointer:
1836       type = cast<MemberPointerType>(ty)->getPointeeType();
1837       break;
1838 
1839     case Type::ConstantArray:
1840     case Type::IncompleteArray:
1841       // Losing element qualification here is fine.
1842       type = cast<ArrayType>(ty)->getElementType();
1843       break;
1844 
1845     case Type::VariableArray: {
1846       // Losing element qualification here is fine.
1847       const VariableArrayType *vat = cast<VariableArrayType>(ty);
1848 
1849       // Unknown size indication requires no size computation.
1850       // Otherwise, evaluate and record it.
1851       if (const Expr *size = vat->getSizeExpr()) {
1852         // It's possible that we might have emitted this already,
1853         // e.g. with a typedef and a pointer to it.
1854         llvm::Value *&entry = VLASizeMap[size];
1855         if (!entry) {
1856           llvm::Value *Size = EmitScalarExpr(size);
1857 
1858           // C11 6.7.6.2p5:
1859           //   If the size is an expression that is not an integer constant
1860           //   expression [...] each time it is evaluated it shall have a value
1861           //   greater than zero.
1862           if (SanOpts.has(SanitizerKind::VLABound) &&
1863               size->getType()->isSignedIntegerType()) {
1864             SanitizerScope SanScope(this);
1865             llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1866             llvm::Constant *StaticArgs[] = {
1867               EmitCheckSourceLocation(size->getLocStart()),
1868               EmitCheckTypeDescriptor(size->getType())
1869             };
1870             EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
1871                                      SanitizerKind::VLABound),
1872                       SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
1873           }
1874 
1875           // Always zexting here would be wrong if it weren't
1876           // undefined behavior to have a negative bound.
1877           entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
1878         }
1879       }
1880       type = vat->getElementType();
1881       break;
1882     }
1883 
1884     case Type::FunctionProto:
1885     case Type::FunctionNoProto:
1886       type = cast<FunctionType>(ty)->getReturnType();
1887       break;
1888 
1889     case Type::Paren:
1890     case Type::TypeOf:
1891     case Type::UnaryTransform:
1892     case Type::Attributed:
1893     case Type::SubstTemplateTypeParm:
1894     case Type::PackExpansion:
1895       // Keep walking after single level desugaring.
1896       type = type.getSingleStepDesugaredType(getContext());
1897       break;
1898 
1899     case Type::Typedef:
1900     case Type::Decltype:
1901     case Type::Auto:
1902       // Stop walking: nothing to do.
1903       return;
1904 
1905     case Type::TypeOfExpr:
1906       // Stop walking: emit typeof expression.
1907       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1908       return;
1909 
1910     case Type::Atomic:
1911       type = cast<AtomicType>(ty)->getValueType();
1912       break;
1913 
1914     case Type::Pipe:
1915       type = cast<PipeType>(ty)->getElementType();
1916       break;
1917     }
1918   } while (type->isVariablyModifiedType());
1919 }
1920 
1921 Address CodeGenFunction::EmitVAListRef(const Expr* E) {
1922   if (getContext().getBuiltinVaListType()->isArrayType())
1923     return EmitPointerWithAlignment(E);
1924   return EmitLValue(E).getAddress();
1925 }
1926 
1927 Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
1928   return EmitLValue(E).getAddress();
1929 }
1930 
1931 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
1932                                               const APValue &Init) {
1933   assert(!Init.isUninit() && "Invalid DeclRefExpr initializer!");
1934   if (CGDebugInfo *Dbg = getDebugInfo())
1935     if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
1936       Dbg->EmitGlobalVariable(E->getDecl(), Init);
1937 }
1938 
1939 CodeGenFunction::PeepholeProtection
1940 CodeGenFunction::protectFromPeepholes(RValue rvalue) {
1941   // At the moment, the only aggressive peephole we do in IR gen
1942   // is trunc(zext) folding, but if we add more, we can easily
1943   // extend this protection.
1944 
1945   if (!rvalue.isScalar()) return PeepholeProtection();
1946   llvm::Value *value = rvalue.getScalarVal();
1947   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
1948 
1949   // Just make an extra bitcast.
1950   assert(HaveInsertPoint());
1951   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
1952                                                   Builder.GetInsertBlock());
1953 
1954   PeepholeProtection protection;
1955   protection.Inst = inst;
1956   return protection;
1957 }
1958 
1959 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
1960   if (!protection.Inst) return;
1961 
1962   // In theory, we could try to duplicate the peepholes now, but whatever.
1963   protection.Inst->eraseFromParent();
1964 }
1965 
1966 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
1967                                                  llvm::Value *AnnotatedVal,
1968                                                  StringRef AnnotationStr,
1969                                                  SourceLocation Location) {
1970   llvm::Value *Args[4] = {
1971     AnnotatedVal,
1972     Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
1973     Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
1974     CGM.EmitAnnotationLineNo(Location)
1975   };
1976   return Builder.CreateCall(AnnotationFn, Args);
1977 }
1978 
1979 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
1980   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1981   // FIXME We create a new bitcast for every annotation because that's what
1982   // llvm-gcc was doing.
1983   for (const auto *I : D->specific_attrs<AnnotateAttr>())
1984     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
1985                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
1986                        I->getAnnotation(), D->getLocation());
1987 }
1988 
1989 Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
1990                                               Address Addr) {
1991   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1992   llvm::Value *V = Addr.getPointer();
1993   llvm::Type *VTy = V->getType();
1994   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
1995                                     CGM.Int8PtrTy);
1996 
1997   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
1998     // FIXME Always emit the cast inst so we can differentiate between
1999     // annotation on the first field of a struct and annotation on the struct
2000     // itself.
2001     if (VTy != CGM.Int8PtrTy)
2002       V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
2003     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
2004     V = Builder.CreateBitCast(V, VTy);
2005   }
2006 
2007   return Address(V, Addr.getAlignment());
2008 }
2009 
2010 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
2011 
2012 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
2013     : CGF(CGF) {
2014   assert(!CGF->IsSanitizerScope);
2015   CGF->IsSanitizerScope = true;
2016 }
2017 
2018 CodeGenFunction::SanitizerScope::~SanitizerScope() {
2019   CGF->IsSanitizerScope = false;
2020 }
2021 
2022 void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2023                                    const llvm::Twine &Name,
2024                                    llvm::BasicBlock *BB,
2025                                    llvm::BasicBlock::iterator InsertPt) const {
2026   LoopStack.InsertHelper(I);
2027   if (IsSanitizerScope)
2028     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
2029 }
2030 
2031 void CGBuilderInserter::InsertHelper(
2032     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
2033     llvm::BasicBlock::iterator InsertPt) const {
2034   llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
2035   if (CGF)
2036     CGF->InsertHelper(I, Name, BB, InsertPt);
2037 }
2038 
2039 static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
2040                                 CodeGenModule &CGM, const FunctionDecl *FD,
2041                                 std::string &FirstMissing) {
2042   // If there aren't any required features listed then go ahead and return.
2043   if (ReqFeatures.empty())
2044     return false;
2045 
2046   // Now build up the set of caller features and verify that all the required
2047   // features are there.
2048   llvm::StringMap<bool> CallerFeatureMap;
2049   CGM.getFunctionFeatureMap(CallerFeatureMap, FD);
2050 
2051   // If we have at least one of the features in the feature list return
2052   // true, otherwise return false.
2053   return std::all_of(
2054       ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
2055         SmallVector<StringRef, 1> OrFeatures;
2056         Feature.split(OrFeatures, "|");
2057         return std::any_of(OrFeatures.begin(), OrFeatures.end(),
2058                            [&](StringRef Feature) {
2059                              if (!CallerFeatureMap.lookup(Feature)) {
2060                                FirstMissing = Feature.str();
2061                                return false;
2062                              }
2063                              return true;
2064                            });
2065       });
2066 }
2067 
2068 // Emits an error if we don't have a valid set of target features for the
2069 // called function.
2070 void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
2071                                           const FunctionDecl *TargetDecl) {
2072   // Early exit if this is an indirect call.
2073   if (!TargetDecl)
2074     return;
2075 
2076   // Get the current enclosing function if it exists. If it doesn't
2077   // we can't check the target features anyhow.
2078   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
2079   if (!FD)
2080     return;
2081 
2082   // Grab the required features for the call. For a builtin this is listed in
2083   // the td file with the default cpu, for an always_inline function this is any
2084   // listed cpu and any listed features.
2085   unsigned BuiltinID = TargetDecl->getBuiltinID();
2086   std::string MissingFeature;
2087   if (BuiltinID) {
2088     SmallVector<StringRef, 1> ReqFeatures;
2089     const char *FeatureList =
2090         CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
2091     // Return if the builtin doesn't have any required features.
2092     if (!FeatureList || StringRef(FeatureList) == "")
2093       return;
2094     StringRef(FeatureList).split(ReqFeatures, ",");
2095     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
2096       CGM.getDiags().Report(E->getLocStart(), diag::err_builtin_needs_feature)
2097           << TargetDecl->getDeclName()
2098           << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
2099 
2100   } else if (TargetDecl->hasAttr<TargetAttr>()) {
2101     // Get the required features for the callee.
2102     SmallVector<StringRef, 1> ReqFeatures;
2103     llvm::StringMap<bool> CalleeFeatureMap;
2104     CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2105     for (const auto &F : CalleeFeatureMap) {
2106       // Only positive features are "required".
2107       if (F.getValue())
2108         ReqFeatures.push_back(F.getKey());
2109     }
2110     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
2111       CGM.getDiags().Report(E->getLocStart(), diag::err_function_needs_feature)
2112           << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
2113   }
2114 }
2115 
2116 void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2117   if (!CGM.getCodeGenOpts().SanitizeStats)
2118     return;
2119 
2120   llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2121   IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2122   CGM.getSanStats().create(IRB, SSK);
2123 }
2124 
2125 llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
2126   if (CGDebugInfo *DI = getDebugInfo())
2127     return DI->SourceLocToDebugLoc(Location);
2128 
2129   return llvm::DebugLoc();
2130 }
2131