1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the per-function state used while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
16 #include "CGCleanup.h"
17 #include "CGCUDARuntime.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;
41 /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
43 static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
44 const LangOptions &LangOpts) {
45 if (CGOpts.DisableLifetimeMarkers)
48 // Asan uses markers for use-after-scope checks.
49 if (CGOpts.SanitizeAddressUseAfterScope)
52 // Disable lifetime markers in msan builds.
53 // FIXME: Remove this when msan works with lifetime markers.
54 if (LangOpts.Sanitize.has(SanitizerKind::Memory))
57 // For now, only in optimized builds.
58 return CGOpts.OptimizationLevel != 0;
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();
87 llvm::FastMathFlags FMF;
88 if (CGM.getLangOpts().FastMath)
89 FMF.setUnsafeAlgebra();
90 if (CGM.getLangOpts().FiniteMathOnly) {
94 if (CGM.getCodeGenOpts().NoNaNsFPMath) {
97 if (CGM.getCodeGenOpts().NoSignedZeros) {
98 FMF.setNoSignedZeros();
100 if (CGM.getCodeGenOpts().ReciprocalMath) {
101 FMF.setAllowReciprocal();
103 Builder.setFastMathFlags(FMF);
106 CodeGenFunction::~CodeGenFunction() {
107 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
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
113 destroyBlockInfos(FirstBlockInfo);
115 if (getLangOpts().OpenMP && CurFn)
116 CGM.getOpenMPRuntime().functionFinished(*this);
119 CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
120 AlignmentSource *Source) {
121 return getNaturalTypeAlignment(T->getPointeeType(), Source,
122 /*forPointee*/ true);
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);
138 if (Source) *Source = AlignmentSource::Type;
141 if (T->isIncompleteType()) {
142 Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
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);
151 Alignment = getContext().getTypeAlignInChars(T);
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);
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,
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.
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);
182 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
183 return CGM.getTypes().ConvertTypeForMem(T);
186 llvm::Type *CodeGenFunction::ConvertType(QualType T) {
187 return CGM.getTypes().ConvertType(T);
190 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
191 type = type.getCanonicalType();
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");
203 llvm_unreachable("undeduced auto type in IR-generation");
205 // Various scalar types.
208 case Type::BlockPointer:
209 case Type::LValueReference:
210 case Type::RValueReference:
211 case Type::MemberPointer:
213 case Type::ExtVector:
214 case Type::FunctionProto:
215 case Type::FunctionNoProto:
217 case Type::ObjCObjectPointer:
225 // Arrays, records, and Objective-C objects.
226 case Type::ConstantArray:
227 case Type::IncompleteArray:
228 case Type::VariableArray:
230 case Type::ObjCObject:
231 case Type::ObjCInterface:
232 return TEK_Aggregate;
234 // We operate on atomic values according to their underlying type.
236 type = cast<AtomicType>(type)->getValueType();
239 llvm_unreachable("unknown type kind!");
243 llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
244 // For cleanliness, we try to avoid emitting the return block for
246 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
249 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
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();
257 EmitBlock(ReturnBlock.getBlock());
258 return llvm::DebugLoc();
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();
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.
283 EmitBlock(ReturnBlock.getBlock());
284 return llvm::DebugLoc();
287 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
289 if (!BB->use_empty())
290 return CGF.CurFn->getBasicBlockList().push_back(BB);
294 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
295 assert(BreakContinueStack.empty() &&
296 "mismatched push/pop in break/continue stack!");
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.
310 // If there are multiple branches to the return block, the branch
311 // instructions will get the location of the return statements and
313 if (CGDebugInfo *DI = getDebugInfo()) {
314 if (OnlySimpleReturnStmts)
315 DI->EmitLocation(Builder, LastStopPoint);
317 DI->EmitLocation(Builder, EndLoc);
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;
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);
335 PopCleanupBlocks(PrologueCleanupDepth);
338 // Emit function epilog (to return).
339 llvm::DebugLoc Loc = EmitReturnBlock();
341 if (ShouldInstrumentFunction())
342 EmitFunctionInstrumentation("__cyg_profile_func_exit");
344 // Emit debug descriptor for function end.
345 if (CGDebugInfo *DI = getDebugInfo())
346 DI->EmitFunctionEnd(Builder);
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);
354 assert(EHStack.empty() &&
355 "did not remove all scopes from cleanup stack!");
357 // If someone did an indirect goto, emit the indirect goto block at the end of
359 if (IndirectBranch) {
360 EmitBlock(IndirectBranch->getParent());
361 Builder.ClearInsertionPoint();
364 // If some of our locals escaped, insert a call to llvm.localescape in the
366 if (!EscapedLocals.empty()) {
367 // Invert the map from local to index into a simple vector. There should be
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);
378 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
379 llvm::Instruction *Ptr = AllocaInsertPt;
380 AllocaInsertPt = nullptr;
381 Ptr->eraseFromParent();
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();
393 EmitIfUsed(*this, EHResumeBlock);
394 EmitIfUsed(*this, TerminateLandingPad);
395 EmitIfUsed(*this, TerminateHandler);
396 EmitIfUsed(*this, UnreachableBlock);
398 if (CGM.getCodeGenOpts().EmitDeclMetadata)
401 for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
402 I = DeferredReplacements.begin(),
403 E = DeferredReplacements.end();
405 I->first->replaceAllUsesWith(I->second);
406 I->first->eraseFromParent();
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)
415 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
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;
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);
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),
443 llvm::Value *args[] = {
444 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
448 EmitNounwindRuntimeCall(F, args);
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);
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);
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);
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) {
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.
484 return 0; // Assume private.
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.
498 const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
500 // MDNode for the kernel argument address space qualifiers.
501 SmallVector<llvm::Metadata *, 8> addressQuals;
503 // MDNode for the kernel argument access qualifiers (images only).
504 SmallVector<llvm::Metadata *, 8> accessQuals;
506 // MDNode for the kernel argument type names.
507 SmallVector<llvm::Metadata *, 8> argTypeNames;
509 // MDNode for the kernel argument base type names.
510 SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
512 // MDNode for the kernel argument type qualifiers.
513 SmallVector<llvm::Metadata *, 8> argTypeQuals;
515 // MDNode for the kernel argument names.
516 SmallVector<llvm::Metadata *, 8> argNames;
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;
523 if (ty->isPointerType()) {
524 QualType pointeeTy = ty->getPointeeType();
526 // Get address qualifier.
527 addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
528 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
530 // Get argument type name.
531 std::string typeName =
532 pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
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);
539 argTypeNames.push_back(llvm::MDString::get(Context, typeName));
541 std::string baseTypeName =
542 pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
546 // Turn "unsigned type" to "utype"
547 pos = baseTypeName.find("unsigned");
548 if (pos != std::string::npos)
549 baseTypeName.erase(pos+1, 8);
551 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
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";
562 uint32_t AddrSpc = 0;
563 bool isPipe = ty->isPipeType();
564 if (ty->isImageType() || isPipe)
565 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
567 addressQuals.push_back(
568 llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
570 // Get argument type name.
571 std::string typeName;
573 typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType()
574 .getAsString(Policy);
576 typeName = ty.getUnqualifiedType().getAsString(Policy);
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);
583 std::string baseTypeName;
585 baseTypeName = ty.getCanonicalType()->getAs<PipeType>()
586 ->getElementType().getCanonicalType()
587 .getAsString(Policy);
590 ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
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);
601 argTypeNames.push_back(llvm::MDString::get(Context, typeName));
603 // Turn "unsigned type" to "utype"
604 pos = baseTypeName.find("unsigned");
605 if (pos != std::string::npos)
606 baseTypeName.erase(pos+1, 8);
608 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
610 // Get argument type qualifiers:
611 if (ty.isConstQualified())
613 if (ty.isVolatileQualified())
614 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
619 argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
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"));
629 accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
631 accessQuals.push_back(llvm::MDString::get(Context, "none"));
633 // Get argument name.
634 argNames.push_back(llvm::MDString::get(Context, parm->getName()));
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));
652 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
655 if (!FD->hasAttr<OpenCLKernelAttr>())
658 llvm::LLVMContext &Context = getLLVMContext();
660 GenOpenCLArgMetadata(FD, Fn, CGM, Context, Builder, getContext());
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));
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));
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));
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();
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);
710 void CodeGenFunction::StartFunction(GlobalDecl GD,
713 const CGFunctionInfo &FnInfo,
714 const FunctionArgList &Args,
716 SourceLocation StartLoc) {
718 "Do not use a CodeGenFunction object for more than one function");
720 const Decl *D = GD.getDecl();
722 DidCallStackSave = false;
724 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
725 if (FD->usesSEHTry())
727 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
731 assert(CurFn->isDeclaration() && "Function already has body?");
733 if (CGM.isInSanitizerBlacklist(Fn, Loc))
737 // Apply the no_sanitize* attributes to SanOpts.
738 for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
739 SanOpts.Mask &= ~Attr->getMask();
742 // Apply sanitizer attributes to the function.
743 if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
744 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
745 if (SanOpts.has(SanitizerKind::Thread))
746 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
747 if (SanOpts.has(SanitizerKind::Memory))
748 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
749 if (SanOpts.has(SanitizerKind::SafeStack))
750 Fn->addFnAttr(llvm::Attribute::SafeStack);
752 // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
753 // .cxx_destruct and all of their calees at run time.
754 if (SanOpts.has(SanitizerKind::Thread)) {
755 if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
756 IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
757 if (OMD->getMethodFamily() == OMF_dealloc ||
758 OMD->getMethodFamily() == OMF_initialize ||
759 (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
760 Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
761 Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
766 // Apply xray attributes to the function (as a string, for now)
767 if (D && ShouldXRayInstrumentFunction()) {
768 if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
769 if (XRayAttr->alwaysXRayInstrument())
770 Fn->addFnAttr("function-instrument", "xray-always");
771 if (XRayAttr->neverXRayInstrument())
772 Fn->addFnAttr("function-instrument", "xray-never");
775 "xray-instruction-threshold",
776 llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
780 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
781 if (CGM.getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
782 CGM.getOpenMPRuntime().emitDeclareSimdFunction(FD, Fn);
784 // Add no-jump-tables value.
785 Fn->addFnAttr("no-jump-tables",
786 llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
788 if (getLangOpts().OpenCL) {
789 // Add metadata for a kernel function.
790 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
791 EmitOpenCLKernelMetadata(FD, Fn);
794 // If we are checking function types, emit a function type signature as
796 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
797 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
798 if (llvm::Constant *PrologueSig =
799 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
800 llvm::Constant *FTRTTIConst =
801 CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
802 llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
803 llvm::Constant *PrologueStructConst =
804 llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
805 Fn->setPrologueData(PrologueStructConst);
810 // If we're in C++ mode and the function name is "main", it is guaranteed
811 // to be norecurse by the standard (3.6.1.3 "The function main shall not be
812 // used within a program").
813 if (getLangOpts().CPlusPlus)
814 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
816 Fn->addFnAttr(llvm::Attribute::NoRecurse);
818 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
820 // Create a marker to make it easy to insert allocas into the entryblock
821 // later. Don't create this with the builder, because we don't want it
823 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
824 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
826 ReturnBlock = getJumpDestInCurrentScope("return");
828 Builder.SetInsertPoint(EntryBB);
830 // Emit subprogram debug descriptor.
831 if (CGDebugInfo *DI = getDebugInfo()) {
832 // Reconstruct the type from the argument list so that implicit parameters,
833 // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
835 CallingConv CC = CallingConv::CC_C;
836 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
837 if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
838 CC = SrcFnTy->getCallConv();
839 SmallVector<QualType, 16> ArgTypes;
840 for (const VarDecl *VD : Args)
841 ArgTypes.push_back(VD->getType());
842 QualType FnType = getContext().getFunctionType(
843 RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
844 DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
847 if (ShouldInstrumentFunction())
848 EmitFunctionInstrumentation("__cyg_profile_func_enter");
850 // Since emitting the mcount call here impacts optimizations such as function
851 // inlining, we just add an attribute to insert a mcount call in backend.
852 // The attribute "counting-function" is set to mcount function name which is
853 // architecture dependent.
854 if (CGM.getCodeGenOpts().InstrumentForProfiling)
855 Fn->addFnAttr("counting-function", getTarget().getMCountName());
857 if (RetTy->isVoidType()) {
858 // Void type; nothing to return.
859 ReturnValue = Address::invalid();
861 // Count the implicit return.
862 if (!endsWithReturn(D))
864 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
865 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
866 // Indirect aggregate return; emit returned value directly into sret slot.
867 // This reduces code size, and affects correctness in C++.
868 auto AI = CurFn->arg_begin();
869 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
871 ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
872 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
873 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
874 // Load the sret pointer from the argument struct and return into that.
875 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
876 llvm::Function::arg_iterator EI = CurFn->arg_end();
878 llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
879 Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
880 ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
882 ReturnValue = CreateIRTemp(RetTy, "retval");
884 // Tell the epilog emitter to autorelease the result. We do this
885 // now so that various specialized functions can suppress it
886 // during their IR-generation.
887 if (getLangOpts().ObjCAutoRefCount &&
888 !CurFnInfo->isReturnsRetained() &&
889 RetTy->isObjCRetainableType())
890 AutoreleaseResult = true;
893 EmitStartEHSpec(CurCodeDecl);
895 PrologueCleanupDepth = EHStack.stable_begin();
896 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
898 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
899 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
900 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
901 if (MD->getParent()->isLambda() &&
902 MD->getOverloadedOperator() == OO_Call) {
903 // We're in a lambda; figure out the captures.
904 MD->getParent()->getCaptureFields(LambdaCaptureFields,
905 LambdaThisCaptureField);
906 if (LambdaThisCaptureField) {
907 // If the lambda captures the object referred to by '*this' - either by
908 // value or by reference, make sure CXXThisValue points to the correct
911 // Get the lvalue for the field (which is a copy of the enclosing object
912 // or contains the address of the enclosing object).
913 LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
914 if (!LambdaThisCaptureField->getType()->isPointerType()) {
915 // If the enclosing object was captured by value, just use its address.
916 CXXThisValue = ThisFieldLValue.getAddress().getPointer();
918 // Load the lvalue pointed to by the field, since '*this' was captured
921 EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
924 for (auto *FD : MD->getParent()->fields()) {
925 if (FD->hasCapturedVLAType()) {
926 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
927 SourceLocation()).getScalarVal();
928 auto VAT = FD->getCapturedVLAType();
929 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
933 // Not in a lambda; just use 'this' from the method.
934 // FIXME: Should we generate a new load for each use of 'this'? The
935 // fast register allocator would be happier...
936 CXXThisValue = CXXABIThisValue;
940 // If any of the arguments have a variably modified type, make sure to
941 // emit the type size.
942 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
944 const VarDecl *VD = *i;
946 // Dig out the type as written from ParmVarDecls; it's unclear whether
947 // the standard (C99 6.9.1p10) requires this, but we're following the
948 // precedent set by gcc.
950 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
951 Ty = PVD->getOriginalType();
955 if (Ty->isVariablyModifiedType())
956 EmitVariablyModifiedType(Ty);
958 // Emit a location at the end of the prologue.
959 if (CGDebugInfo *DI = getDebugInfo())
960 DI->EmitLocation(Builder, StartLoc);
963 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
965 incrementProfileCounter(Body);
966 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
967 EmitCompoundStmtWithoutScope(*S);
972 /// When instrumenting to collect profile data, the counts for some blocks
973 /// such as switch cases need to not include the fall-through counts, so
974 /// emit a branch around the instrumentation code. When not instrumenting,
975 /// this just calls EmitBlock().
976 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
978 llvm::BasicBlock *SkipCountBB = nullptr;
979 if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
980 // When instrumenting for profiling, the fallthrough to certain
981 // statements needs to skip over the instrumentation code so that we
982 // get an accurate count.
983 SkipCountBB = createBasicBlock("skipcount");
984 EmitBranch(SkipCountBB);
987 uint64_t CurrentCount = getCurrentProfileCount();
988 incrementProfileCounter(S);
989 setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
991 EmitBlock(SkipCountBB);
994 /// Tries to mark the given function nounwind based on the
995 /// non-existence of any throwing calls within it. We believe this is
996 /// lightweight enough to do at -O0.
997 static void TryMarkNoThrow(llvm::Function *F) {
998 // LLVM treats 'nounwind' on a function as part of the type, so we
999 // can't do this on functions that can be overwritten.
1000 if (F->isInterposable()) return;
1002 for (llvm::BasicBlock &BB : *F)
1003 for (llvm::Instruction &I : BB)
1007 F->setDoesNotThrow();
1010 QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1011 FunctionArgList &Args) {
1012 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1013 QualType ResTy = FD->getReturnType();
1015 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1016 if (MD && MD->isInstance()) {
1017 if (CGM.getCXXABI().HasThisReturn(GD))
1018 ResTy = MD->getThisType(getContext());
1019 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1020 ResTy = CGM.getContext().VoidPtrTy;
1021 CGM.getCXXABI().buildThisParam(*this, Args);
1024 // The base version of an inheriting constructor whose constructed base is a
1025 // virtual base is not passed any arguments (because it doesn't actually call
1026 // the inherited constructor).
1027 bool PassedParams = true;
1028 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1029 if (auto Inherited = CD->getInheritedConstructor())
1031 getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1034 for (auto *Param : FD->parameters()) {
1035 Args.push_back(Param);
1036 if (!Param->hasAttr<PassObjectSizeAttr>())
1039 IdentifierInfo *NoID = nullptr;
1040 auto *Implicit = ImplicitParamDecl::Create(
1041 getContext(), Param->getDeclContext(), Param->getLocation(), NoID,
1042 getContext().getSizeType());
1043 SizeArguments[Param] = Implicit;
1044 Args.push_back(Implicit);
1048 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1049 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1055 shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
1056 const ASTContext &Context) {
1057 QualType T = FD->getReturnType();
1058 // Avoid the optimization for functions that return a record type with a
1059 // trivial destructor or another trivially copyable type.
1060 if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
1061 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1062 return !ClassDecl->hasTrivialDestructor();
1064 return !T.isTriviallyCopyableType(Context);
1067 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1068 const CGFunctionInfo &FnInfo) {
1069 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1072 FunctionArgList Args;
1073 QualType ResTy = BuildFunctionArgList(GD, Args);
1075 // Check if we should generate debug info for this function.
1076 if (FD->hasAttr<NoDebugAttr>())
1077 DebugInfo = nullptr; // disable debug info indefinitely for this function
1079 SourceRange BodyRange;
1080 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
1081 CurEHLocation = BodyRange.getEnd();
1083 // Use the location of the start of the function to determine where
1084 // the function definition is located. By default use the location
1085 // of the declaration as the location for the subprogram. A function
1086 // may lack a declaration in the source code if it is created by code
1087 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1088 SourceLocation Loc = FD->getLocation();
1090 // If this is a function specialization then use the pattern body
1091 // as the location for the function.
1092 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1093 if (SpecDecl->hasBody(SpecDecl))
1094 Loc = SpecDecl->getLocation();
1096 Stmt *Body = FD->getBody();
1098 // Initialize helper which will detect jumps which can cause invalid lifetime
1100 if (Body && ShouldEmitLifetimeMarkers)
1101 Bypasses.Init(Body);
1103 // Emit the standard function prologue.
1104 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1106 // Generate the body of the function.
1107 PGO.assignRegionCounters(GD, CurFn);
1108 if (isa<CXXDestructorDecl>(FD))
1109 EmitDestructorBody(Args);
1110 else if (isa<CXXConstructorDecl>(FD))
1111 EmitConstructorBody(Args);
1112 else if (getLangOpts().CUDA &&
1113 !getLangOpts().CUDAIsDevice &&
1114 FD->hasAttr<CUDAGlobalAttr>())
1115 CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1116 else if (isa<CXXConversionDecl>(FD) &&
1117 cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
1118 // The lambda conversion to block pointer is special; the semantics can't be
1119 // expressed in the AST, so IRGen needs to special-case it.
1120 EmitLambdaToBlockPointerBody(Args);
1121 } else if (isa<CXXMethodDecl>(FD) &&
1122 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1123 // The lambda static invoker function is special, because it forwards or
1124 // clones the body of the function call operator (but is actually static).
1125 EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
1126 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1127 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1128 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1129 // Implicit copy-assignment gets the same special treatment as implicit
1130 // copy-constructors.
1131 emitImplicitAssignmentOperatorBody(Args);
1133 EmitFunctionBody(Args, Body);
1135 llvm_unreachable("no definition for emitted function");
1137 // C++11 [stmt.return]p2:
1138 // Flowing off the end of a function [...] results in undefined behavior in
1139 // a value-returning function.
1141 // If the '}' that terminates a function is reached, and the value of the
1142 // function call is used by the caller, the behavior is undefined.
1143 if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
1144 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1145 bool ShouldEmitUnreachable =
1146 CGM.getCodeGenOpts().StrictReturn ||
1147 shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
1148 if (SanOpts.has(SanitizerKind::Return)) {
1149 SanitizerScope SanScope(this);
1150 llvm::Value *IsFalse = Builder.getFalse();
1151 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1152 SanitizerHandler::MissingReturn,
1153 EmitCheckSourceLocation(FD->getLocation()), None);
1154 } else if (ShouldEmitUnreachable) {
1155 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1156 EmitTrapCall(llvm::Intrinsic::trap);
1158 if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1159 Builder.CreateUnreachable();
1160 Builder.ClearInsertionPoint();
1164 // Emit the standard function epilogue.
1165 FinishFunction(BodyRange.getEnd());
1167 // If we haven't marked the function nothrow through other means, do
1168 // a quick pass now to see if we can.
1169 if (!CurFn->doesNotThrow())
1170 TryMarkNoThrow(CurFn);
1173 /// ContainsLabel - Return true if the statement contains a label in it. If
1174 /// this statement is not executed normally, it not containing a label means
1175 /// that we can just remove the code.
1176 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1177 // Null statement, not a label!
1178 if (!S) return false;
1180 // If this is a label, we have to emit the code, consider something like:
1181 // if (0) { ... foo: bar(); } goto foo;
1183 // TODO: If anyone cared, we could track __label__'s, since we know that you
1184 // can't jump to one from outside their declared region.
1185 if (isa<LabelStmt>(S))
1188 // If this is a case/default statement, and we haven't seen a switch, we have
1189 // to emit the code.
1190 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1193 // If this is a switch statement, we want to ignore cases below it.
1194 if (isa<SwitchStmt>(S))
1195 IgnoreCaseStmts = true;
1197 // Scan subexpressions for verboten labels.
1198 for (const Stmt *SubStmt : S->children())
1199 if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1205 /// containsBreak - Return true if the statement contains a break out of it.
1206 /// If the statement (recursively) contains a switch or loop with a break
1207 /// inside of it, this is fine.
1208 bool CodeGenFunction::containsBreak(const Stmt *S) {
1209 // Null statement, not a label!
1210 if (!S) return false;
1212 // If this is a switch or loop that defines its own break scope, then we can
1213 // include it and anything inside of it.
1214 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1218 if (isa<BreakStmt>(S))
1221 // Scan subexpressions for verboten breaks.
1222 for (const Stmt *SubStmt : S->children())
1223 if (containsBreak(SubStmt))
1229 bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1230 if (!S) return false;
1232 // Some statement kinds add a scope and thus never add a decl to the current
1233 // scope. Note, this list is longer than the list of statements that might
1234 // have an unscoped decl nested within them, but this way is conservatively
1235 // correct even if more statement kinds are added.
1236 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1237 isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1238 isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1239 isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1242 if (isa<DeclStmt>(S))
1245 for (const Stmt *SubStmt : S->children())
1246 if (mightAddDeclToScope(SubStmt))
1252 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1253 /// to a constant, or if it does but contains a label, return false. If it
1254 /// constant folds return true and set the boolean result in Result.
1255 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1258 llvm::APSInt ResultInt;
1259 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1262 ResultBool = ResultInt.getBoolValue();
1266 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1267 /// to a constant, or if it does but contains a label, return false. If it
1268 /// constant folds return true and set the folded value.
1269 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1270 llvm::APSInt &ResultInt,
1272 // FIXME: Rename and handle conversion of other evaluatable things
1275 if (!Cond->EvaluateAsInt(Int, getContext()))
1276 return false; // Not foldable, not integer or not fully evaluatable.
1278 if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
1279 return false; // Contains a label.
1287 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1288 /// statement) to the specified blocks. Based on the condition, this might try
1289 /// to simplify the codegen of the conditional based on the branch.
1291 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1292 llvm::BasicBlock *TrueBlock,
1293 llvm::BasicBlock *FalseBlock,
1294 uint64_t TrueCount) {
1295 Cond = Cond->IgnoreParens();
1297 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1299 // Handle X && Y in a condition.
1300 if (CondBOp->getOpcode() == BO_LAnd) {
1301 // If we have "1 && X", simplify the code. "0 && X" would have constant
1302 // folded if the case was simple enough.
1303 bool ConstantBool = false;
1304 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1306 // br(1 && X) -> br(X).
1307 incrementProfileCounter(CondBOp);
1308 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1312 // If we have "X && 1", simplify the code to use an uncond branch.
1313 // "X && 0" would have been constant folded to 0.
1314 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1316 // br(X && 1) -> br(X).
1317 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1321 // Emit the LHS as a conditional. If the LHS conditional is false, we
1322 // want to jump to the FalseBlock.
1323 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1324 // The counter tells us how often we evaluate RHS, and all of TrueCount
1325 // can be propagated to that branch.
1326 uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1328 ConditionalEvaluation eval(*this);
1330 ApplyDebugLocation DL(*this, Cond);
1331 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1335 incrementProfileCounter(CondBOp);
1336 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1338 // Any temporaries created here are conditional.
1340 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
1346 if (CondBOp->getOpcode() == BO_LOr) {
1347 // If we have "0 || X", simplify the code. "1 || X" would have constant
1348 // folded if the case was simple enough.
1349 bool ConstantBool = false;
1350 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1352 // br(0 || X) -> br(X).
1353 incrementProfileCounter(CondBOp);
1354 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1358 // If we have "X || 0", simplify the code to use an uncond branch.
1359 // "X || 1" would have been constant folded to 1.
1360 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1362 // br(X || 0) -> br(X).
1363 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1367 // Emit the LHS as a conditional. If the LHS conditional is true, we
1368 // want to jump to the TrueBlock.
1369 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1370 // We have the count for entry to the RHS and for the whole expression
1371 // being true, so we can divy up True count between the short circuit and
1374 getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1375 uint64_t RHSCount = TrueCount - LHSCount;
1377 ConditionalEvaluation eval(*this);
1379 ApplyDebugLocation DL(*this, Cond);
1380 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1381 EmitBlock(LHSFalse);
1384 incrementProfileCounter(CondBOp);
1385 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1387 // Any temporaries created here are conditional.
1389 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
1397 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1398 // br(!x, t, f) -> br(x, f, t)
1399 if (CondUOp->getOpcode() == UO_LNot) {
1400 // Negate the count.
1401 uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1402 // Negate the condition and swap the destination blocks.
1403 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1408 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1409 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1410 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1411 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1413 ConditionalEvaluation cond(*this);
1414 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1415 getProfileCount(CondOp));
1417 // When computing PGO branch weights, we only know the overall count for
1418 // the true block. This code is essentially doing tail duplication of the
1419 // naive code-gen, introducing new edges for which counts are not
1420 // available. Divide the counts proportionally between the LHS and RHS of
1421 // the conditional operator.
1422 uint64_t LHSScaledTrueCount = 0;
1425 getProfileCount(CondOp) / (double)getCurrentProfileCount();
1426 LHSScaledTrueCount = TrueCount * LHSRatio;
1430 EmitBlock(LHSBlock);
1431 incrementProfileCounter(CondOp);
1433 ApplyDebugLocation DL(*this, Cond);
1434 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1435 LHSScaledTrueCount);
1440 EmitBlock(RHSBlock);
1441 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1442 TrueCount - LHSScaledTrueCount);
1448 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1449 // Conditional operator handling can give us a throw expression as a
1450 // condition for a case like:
1451 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1453 // br(c, throw x, br(y, t, f))
1454 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1458 // If the branch has a condition wrapped by __builtin_unpredictable,
1459 // create metadata that specifies that the branch is unpredictable.
1460 // Don't bother if not optimizing because that metadata would not be used.
1461 llvm::MDNode *Unpredictable = nullptr;
1462 auto *Call = dyn_cast<CallExpr>(Cond);
1463 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1464 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1465 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1466 llvm::MDBuilder MDHelper(getLLVMContext());
1467 Unpredictable = MDHelper.createUnpredictable();
1471 // Create branch weights based on the number of times we get here and the
1472 // number of times the condition should be true.
1473 uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
1474 llvm::MDNode *Weights =
1475 createProfileWeights(TrueCount, CurrentCount - TrueCount);
1477 // Emit the code with the fully general case.
1480 ApplyDebugLocation DL(*this, Cond);
1481 CondV = EvaluateExprAsBool(Cond);
1483 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1486 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1487 /// specified stmt yet.
1488 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1489 CGM.ErrorUnsupported(S, Type);
1492 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
1493 /// variable-length array whose elements have a non-zero bit-pattern.
1495 /// \param baseType the inner-most element type of the array
1496 /// \param src - a char* pointing to the bit-pattern for a single
1497 /// base element of the array
1498 /// \param sizeInChars - the total size of the VLA, in chars
1499 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1500 Address dest, Address src,
1501 llvm::Value *sizeInChars) {
1502 CGBuilderTy &Builder = CGF.Builder;
1504 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
1505 llvm::Value *baseSizeInChars
1506 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
1509 Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
1511 Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
1513 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1514 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1515 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1517 // Make a loop over the VLA. C99 guarantees that the VLA element
1518 // count must be nonzero.
1519 CGF.EmitBlock(loopBB);
1521 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
1522 cur->addIncoming(begin.getPointer(), originBB);
1524 CharUnits curAlign =
1525 dest.getAlignment().alignmentOfArrayElement(baseSize);
1527 // memcpy the individual element bit-pattern.
1528 Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
1529 /*volatile*/ false);
1531 // Go to the next element.
1533 Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
1535 // Leave if that's the end of the VLA.
1536 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1537 Builder.CreateCondBr(done, contBB, loopBB);
1538 cur->addIncoming(next, loopBB);
1540 CGF.EmitBlock(contBB);
1544 CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1545 // Ignore empty classes in C++.
1546 if (getLangOpts().CPlusPlus) {
1547 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1548 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1553 // Cast the dest ptr to the appropriate i8 pointer type.
1554 if (DestPtr.getElementType() != Int8Ty)
1555 DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1557 // Get size and alignment info for this aggregate.
1558 CharUnits size = getContext().getTypeSizeInChars(Ty);
1560 llvm::Value *SizeVal;
1561 const VariableArrayType *vla;
1563 // Don't bother emitting a zero-byte memset.
1564 if (size.isZero()) {
1565 // But note that getTypeInfo returns 0 for a VLA.
1566 if (const VariableArrayType *vlaType =
1567 dyn_cast_or_null<VariableArrayType>(
1568 getContext().getAsArrayType(Ty))) {
1570 llvm::Value *numElts;
1571 std::tie(numElts, eltType) = getVLASize(vlaType);
1574 CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
1575 if (!eltSize.isOne())
1576 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1582 SizeVal = CGM.getSize(size);
1586 // If the type contains a pointer to data member we can't memset it to zero.
1587 // Instead, create a null constant and copy it to the destination.
1588 // TODO: there are other patterns besides zero that we can usefully memset,
1589 // like -1, which happens to be the pattern used by member-pointers.
1590 if (!CGM.getTypes().isZeroInitializable(Ty)) {
1591 // For a VLA, emit a single element, then splat that over the VLA.
1592 if (vla) Ty = getContext().getBaseElementType(vla);
1594 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1596 llvm::GlobalVariable *NullVariable =
1597 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1598 /*isConstant=*/true,
1599 llvm::GlobalVariable::PrivateLinkage,
1600 NullConstant, Twine());
1601 CharUnits NullAlign = DestPtr.getAlignment();
1602 NullVariable->setAlignment(NullAlign.getQuantity());
1603 Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
1606 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1608 // Get and call the appropriate llvm.memcpy overload.
1609 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
1613 // Otherwise, just memset the whole thing to zero. This is legal
1614 // because in LLVM, all default initializers (other than the ones we just
1615 // handled above) are guaranteed to have a bit pattern of all zeros.
1616 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
1619 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1620 // Make sure that there is a block for the indirect goto.
1621 if (!IndirectBranch)
1622 GetIndirectGotoBlock();
1624 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1626 // Make sure the indirect branch includes all of the address-taken blocks.
1627 IndirectBranch->addDestination(BB);
1628 return llvm::BlockAddress::get(CurFn, BB);
1631 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1632 // If we already made the indirect branch for indirect goto, return its block.
1633 if (IndirectBranch) return IndirectBranch->getParent();
1635 CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
1637 // Create the PHI node that indirect gotos will add entries to.
1638 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1639 "indirect.goto.dest");
1641 // Create the indirect branch instruction.
1642 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1643 return IndirectBranch->getParent();
1646 /// Computes the length of an array in elements, as well as the base
1647 /// element type and a properly-typed first element pointer.
1648 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
1651 const ArrayType *arrayType = origArrayType;
1653 // If it's a VLA, we have to load the stored size. Note that
1654 // this is the size of the VLA in bytes, not its size in elements.
1655 llvm::Value *numVLAElements = nullptr;
1656 if (isa<VariableArrayType>(arrayType)) {
1657 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
1659 // Walk into all VLAs. This doesn't require changes to addr,
1660 // which has type T* where T is the first non-VLA element type.
1662 QualType elementType = arrayType->getElementType();
1663 arrayType = getContext().getAsArrayType(elementType);
1665 // If we only have VLA components, 'addr' requires no adjustment.
1667 baseType = elementType;
1668 return numVLAElements;
1670 } while (isa<VariableArrayType>(arrayType));
1672 // We get out here only if we find a constant array type
1676 // We have some number of constant-length arrays, so addr should
1677 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
1678 // down to the first element of addr.
1679 SmallVector<llvm::Value*, 8> gepIndices;
1681 // GEP down to the array type.
1682 llvm::ConstantInt *zero = Builder.getInt32(0);
1683 gepIndices.push_back(zero);
1685 uint64_t countFromCLAs = 1;
1688 llvm::ArrayType *llvmArrayType =
1689 dyn_cast<llvm::ArrayType>(addr.getElementType());
1690 while (llvmArrayType) {
1691 assert(isa<ConstantArrayType>(arrayType));
1692 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1693 == llvmArrayType->getNumElements());
1695 gepIndices.push_back(zero);
1696 countFromCLAs *= llvmArrayType->getNumElements();
1697 eltType = arrayType->getElementType();
1700 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1701 arrayType = getContext().getAsArrayType(arrayType->getElementType());
1702 assert((!llvmArrayType || arrayType) &&
1703 "LLVM and Clang types are out-of-synch");
1707 // From this point onwards, the Clang array type has been emitted
1708 // as some other type (probably a packed struct). Compute the array
1709 // size, and just emit the 'begin' expression as a bitcast.
1712 cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1713 eltType = arrayType->getElementType();
1714 arrayType = getContext().getAsArrayType(eltType);
1717 llvm::Type *baseType = ConvertType(eltType);
1718 addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
1720 // Create the actual GEP.
1721 addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
1722 gepIndices, "array.begin"),
1723 addr.getAlignment());
1728 llvm::Value *numElements
1729 = llvm::ConstantInt::get(SizeTy, countFromCLAs);
1731 // If we had any VLA dimensions, factor them in.
1733 numElements = Builder.CreateNUWMul(numVLAElements, numElements);
1738 std::pair<llvm::Value*, QualType>
1739 CodeGenFunction::getVLASize(QualType type) {
1740 const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
1741 assert(vla && "type was not a variable array type!");
1742 return getVLASize(vla);
1745 std::pair<llvm::Value*, QualType>
1746 CodeGenFunction::getVLASize(const VariableArrayType *type) {
1747 // The number of elements so far; always size_t.
1748 llvm::Value *numElements = nullptr;
1750 QualType elementType;
1752 elementType = type->getElementType();
1753 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
1754 assert(vlaSize && "no size for VLA!");
1755 assert(vlaSize->getType() == SizeTy);
1758 numElements = vlaSize;
1760 // It's undefined behavior if this wraps around, so mark it that way.
1761 // FIXME: Teach -fsanitize=undefined to trap this.
1762 numElements = Builder.CreateNUWMul(numElements, vlaSize);
1764 } while ((type = getContext().getAsVariableArrayType(elementType)));
1766 return std::pair<llvm::Value*,QualType>(numElements, elementType);
1769 void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
1770 assert(type->isVariablyModifiedType() &&
1771 "Must pass variably modified type to EmitVLASizes!");
1773 EnsureInsertPoint();
1775 // We're going to walk down into the type and look for VLA
1778 assert(type->isVariablyModifiedType());
1780 const Type *ty = type.getTypePtr();
1781 switch (ty->getTypeClass()) {
1783 #define TYPE(Class, Base)
1784 #define ABSTRACT_TYPE(Class, Base)
1785 #define NON_CANONICAL_TYPE(Class, Base)
1786 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1787 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1788 #include "clang/AST/TypeNodes.def"
1789 llvm_unreachable("unexpected dependent type!");
1791 // These types are never variably-modified.
1795 case Type::ExtVector:
1798 case Type::Elaborated:
1799 case Type::TemplateSpecialization:
1800 case Type::ObjCTypeParam:
1801 case Type::ObjCObject:
1802 case Type::ObjCInterface:
1803 case Type::ObjCObjectPointer:
1804 llvm_unreachable("type class is never variably-modified!");
1806 case Type::Adjusted:
1807 type = cast<AdjustedType>(ty)->getAdjustedType();
1811 type = cast<DecayedType>(ty)->getPointeeType();
1815 type = cast<PointerType>(ty)->getPointeeType();
1818 case Type::BlockPointer:
1819 type = cast<BlockPointerType>(ty)->getPointeeType();
1822 case Type::LValueReference:
1823 case Type::RValueReference:
1824 type = cast<ReferenceType>(ty)->getPointeeType();
1827 case Type::MemberPointer:
1828 type = cast<MemberPointerType>(ty)->getPointeeType();
1831 case Type::ConstantArray:
1832 case Type::IncompleteArray:
1833 // Losing element qualification here is fine.
1834 type = cast<ArrayType>(ty)->getElementType();
1837 case Type::VariableArray: {
1838 // Losing element qualification here is fine.
1839 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1841 // Unknown size indication requires no size computation.
1842 // Otherwise, evaluate and record it.
1843 if (const Expr *size = vat->getSizeExpr()) {
1844 // It's possible that we might have emitted this already,
1845 // e.g. with a typedef and a pointer to it.
1846 llvm::Value *&entry = VLASizeMap[size];
1848 llvm::Value *Size = EmitScalarExpr(size);
1851 // If the size is an expression that is not an integer constant
1852 // expression [...] each time it is evaluated it shall have a value
1853 // greater than zero.
1854 if (SanOpts.has(SanitizerKind::VLABound) &&
1855 size->getType()->isSignedIntegerType()) {
1856 SanitizerScope SanScope(this);
1857 llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1858 llvm::Constant *StaticArgs[] = {
1859 EmitCheckSourceLocation(size->getLocStart()),
1860 EmitCheckTypeDescriptor(size->getType())
1862 EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
1863 SanitizerKind::VLABound),
1864 SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
1867 // Always zexting here would be wrong if it weren't
1868 // undefined behavior to have a negative bound.
1869 entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
1872 type = vat->getElementType();
1876 case Type::FunctionProto:
1877 case Type::FunctionNoProto:
1878 type = cast<FunctionType>(ty)->getReturnType();
1883 case Type::UnaryTransform:
1884 case Type::Attributed:
1885 case Type::SubstTemplateTypeParm:
1886 case Type::PackExpansion:
1887 // Keep walking after single level desugaring.
1888 type = type.getSingleStepDesugaredType(getContext());
1892 case Type::Decltype:
1894 // Stop walking: nothing to do.
1897 case Type::TypeOfExpr:
1898 // Stop walking: emit typeof expression.
1899 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1903 type = cast<AtomicType>(ty)->getValueType();
1907 type = cast<PipeType>(ty)->getElementType();
1910 } while (type->isVariablyModifiedType());
1913 Address CodeGenFunction::EmitVAListRef(const Expr* E) {
1914 if (getContext().getBuiltinVaListType()->isArrayType())
1915 return EmitPointerWithAlignment(E);
1916 return EmitLValue(E).getAddress();
1919 Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
1920 return EmitLValue(E).getAddress();
1923 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
1924 const APValue &Init) {
1925 assert(!Init.isUninit() && "Invalid DeclRefExpr initializer!");
1926 if (CGDebugInfo *Dbg = getDebugInfo())
1927 if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
1928 Dbg->EmitGlobalVariable(E->getDecl(), Init);
1931 CodeGenFunction::PeepholeProtection
1932 CodeGenFunction::protectFromPeepholes(RValue rvalue) {
1933 // At the moment, the only aggressive peephole we do in IR gen
1934 // is trunc(zext) folding, but if we add more, we can easily
1935 // extend this protection.
1937 if (!rvalue.isScalar()) return PeepholeProtection();
1938 llvm::Value *value = rvalue.getScalarVal();
1939 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
1941 // Just make an extra bitcast.
1942 assert(HaveInsertPoint());
1943 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
1944 Builder.GetInsertBlock());
1946 PeepholeProtection protection;
1947 protection.Inst = inst;
1951 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
1952 if (!protection.Inst) return;
1954 // In theory, we could try to duplicate the peepholes now, but whatever.
1955 protection.Inst->eraseFromParent();
1958 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
1959 llvm::Value *AnnotatedVal,
1960 StringRef AnnotationStr,
1961 SourceLocation Location) {
1962 llvm::Value *Args[4] = {
1964 Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
1965 Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
1966 CGM.EmitAnnotationLineNo(Location)
1968 return Builder.CreateCall(AnnotationFn, Args);
1971 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
1972 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1973 // FIXME We create a new bitcast for every annotation because that's what
1974 // llvm-gcc was doing.
1975 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1976 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
1977 Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
1978 I->getAnnotation(), D->getLocation());
1981 Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
1983 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1984 llvm::Value *V = Addr.getPointer();
1985 llvm::Type *VTy = V->getType();
1986 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
1989 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
1990 // FIXME Always emit the cast inst so we can differentiate between
1991 // annotation on the first field of a struct and annotation on the struct
1993 if (VTy != CGM.Int8PtrTy)
1994 V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
1995 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
1996 V = Builder.CreateBitCast(V, VTy);
1999 return Address(V, Addr.getAlignment());
2002 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
2004 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
2006 assert(!CGF->IsSanitizerScope);
2007 CGF->IsSanitizerScope = true;
2010 CodeGenFunction::SanitizerScope::~SanitizerScope() {
2011 CGF->IsSanitizerScope = false;
2014 void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2015 const llvm::Twine &Name,
2016 llvm::BasicBlock *BB,
2017 llvm::BasicBlock::iterator InsertPt) const {
2018 LoopStack.InsertHelper(I);
2019 if (IsSanitizerScope)
2020 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
2023 void CGBuilderInserter::InsertHelper(
2024 llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
2025 llvm::BasicBlock::iterator InsertPt) const {
2026 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
2028 CGF->InsertHelper(I, Name, BB, InsertPt);
2031 static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
2032 CodeGenModule &CGM, const FunctionDecl *FD,
2033 std::string &FirstMissing) {
2034 // If there aren't any required features listed then go ahead and return.
2035 if (ReqFeatures.empty())
2038 // Now build up the set of caller features and verify that all the required
2039 // features are there.
2040 llvm::StringMap<bool> CallerFeatureMap;
2041 CGM.getFunctionFeatureMap(CallerFeatureMap, FD);
2043 // If we have at least one of the features in the feature list return
2044 // true, otherwise return false.
2046 ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
2047 SmallVector<StringRef, 1> OrFeatures;
2048 Feature.split(OrFeatures, "|");
2049 return std::any_of(OrFeatures.begin(), OrFeatures.end(),
2050 [&](StringRef Feature) {
2051 if (!CallerFeatureMap.lookup(Feature)) {
2052 FirstMissing = Feature.str();
2060 // Emits an error if we don't have a valid set of target features for the
2062 void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
2063 const FunctionDecl *TargetDecl) {
2064 // Early exit if this is an indirect call.
2068 // Get the current enclosing function if it exists. If it doesn't
2069 // we can't check the target features anyhow.
2070 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
2074 // Grab the required features for the call. For a builtin this is listed in
2075 // the td file with the default cpu, for an always_inline function this is any
2076 // listed cpu and any listed features.
2077 unsigned BuiltinID = TargetDecl->getBuiltinID();
2078 std::string MissingFeature;
2080 SmallVector<StringRef, 1> ReqFeatures;
2081 const char *FeatureList =
2082 CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
2083 // Return if the builtin doesn't have any required features.
2084 if (!FeatureList || StringRef(FeatureList) == "")
2086 StringRef(FeatureList).split(ReqFeatures, ",");
2087 if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
2088 CGM.getDiags().Report(E->getLocStart(), diag::err_builtin_needs_feature)
2089 << TargetDecl->getDeclName()
2090 << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
2092 } else if (TargetDecl->hasAttr<TargetAttr>()) {
2093 // Get the required features for the callee.
2094 SmallVector<StringRef, 1> ReqFeatures;
2095 llvm::StringMap<bool> CalleeFeatureMap;
2096 CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2097 for (const auto &F : CalleeFeatureMap) {
2098 // Only positive features are "required".
2100 ReqFeatures.push_back(F.getKey());
2102 if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
2103 CGM.getDiags().Report(E->getLocStart(), diag::err_function_needs_feature)
2104 << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
2108 void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2109 if (!CGM.getCodeGenOpts().SanitizeStats)
2112 llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2113 IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2114 CGM.getSanStats().create(IRB, SSK);
2117 llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
2118 if (CGDebugInfo *DI = getDebugInfo())
2119 return DI->SourceLocToDebugLoc(Location);
2121 return llvm::DebugLoc();