35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/MDBuilder.h"
38 #include "llvm/IR/Operator.h"
39 using namespace clang;
40 using namespace CodeGen;
46 if (CGOpts.DisableLifetimeMarkers)
55 if (CGOpts.SanitizeAddressUseAfterScope)
59 return CGOpts.OptimizationLevel != 0;
62 CodeGenFunction::CodeGenFunction(
CodeGenModule &cgm,
bool suppressNewContext)
64 Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
66 CurFn(nullptr), ReturnValue(
Address::invalid()),
67 CapturedStmtInfo(nullptr), SanOpts(CGM.getLangOpts().Sanitize),
68 IsSanitizerScope(
false), CurFuncIsThunk(
false), AutoreleaseResult(
false),
69 SawAsmBlock(
false), IsOutlinedSEHHelper(
false), BlockInfo(nullptr),
70 BlockPointer(nullptr), LambdaThisCaptureField(nullptr),
71 NormalCleanupDest(nullptr), NextCleanupDestIndex(1),
72 FirstBlockInfo(nullptr), EHResumeBlock(nullptr), ExceptionSlot(nullptr),
73 EHSelectorSlot(nullptr), DebugInfo(CGM.getModuleDebugInfo()),
74 DisableDebugInfo(
false), DidCallStackSave(
false), IndirectBranch(nullptr),
75 PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
76 CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
77 NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
78 CXXABIThisValue(nullptr), CXXThisValue(nullptr),
79 CXXStructorImplicitParamDecl(nullptr),
80 CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
81 CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
82 TerminateHandler(nullptr), TrapBB(nullptr),
83 ShouldEmitLifetimeMarkers(
85 if (!suppressNewContext)
88 llvm::FastMathFlags FMF;
90 FMF.setUnsafeAlgebra();
99 FMF.setNoSignedZeros();
102 FMF.setAllowReciprocal();
128 bool forPointeeType) {
133 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
161 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
199 #define TYPE(name, parent)
200 #define ABSTRACT_TYPE(name, parent)
201 #define NON_CANONICAL_TYPE(name, parent) case Type::name:
202 #define DEPENDENT_TYPE(name, parent) case Type::name:
203 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
204 #include "clang/AST/TypeNodes.def"
205 llvm_unreachable(
"non-canonical or dependent type in IR-generation");
208 case Type::DeducedTemplateSpecialization:
209 llvm_unreachable(
"undeduced type in IR-generation");
214 case Type::BlockPointer:
215 case Type::LValueReference:
216 case Type::RValueReference:
217 case Type::MemberPointer:
219 case Type::ExtVector:
220 case Type::FunctionProto:
221 case Type::FunctionNoProto:
223 case Type::ObjCObjectPointer:
232 case Type::ConstantArray:
233 case Type::IncompleteArray:
234 case Type::VariableArray:
236 case Type::ObjCObject:
237 case Type::ObjCInterface:
242 type = cast<AtomicType>(
type)->getValueType();
245 llvm_unreachable(
"unknown type kind!");
252 llvm::BasicBlock *CurBB =
Builder.GetInsertBlock();
255 assert(!CurBB->getTerminator() &&
"Unexpected terminated block.");
264 return llvm::DebugLoc();
271 llvm::BranchInst *BI =
273 if (BI && BI->isUnconditional() &&
277 llvm::DebugLoc Loc = BI->getDebugLoc();
278 Builder.SetInsertPoint(BI->getParent());
279 BI->eraseFromParent();
290 return llvm::DebugLoc();
295 if (!BB->use_empty())
296 return CGF.
CurFn->getBasicBlockList().push_back(BB);
301 assert(BreakContinueStack.empty() &&
302 "mismatched push/pop in break/continue stack!");
304 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
305 && NumSimpleReturnExprs == NumReturnExprs
320 if (OnlySimpleReturnStmts)
321 DI->EmitLocation(
Builder, LastStopPoint);
323 DI->EmitLocation(
Builder, EndLoc);
331 bool HasOnlyLifetimeMarkers =
333 bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
338 if (OnlySimpleReturnStmts)
339 DI->EmitLocation(
Builder, EndLoc);
361 "did not remove all scopes from cleanup stack!");
365 if (IndirectBranch) {
372 if (!EscapedLocals.empty()) {
376 EscapeArgs.resize(EscapedLocals.size());
377 for (
auto &Pair : EscapedLocals)
378 EscapeArgs[Pair.second] = Pair.first;
379 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
387 Ptr->eraseFromParent();
391 if (IndirectBranch) {
392 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
393 if (PN->getNumIncomingValues() == 0) {
394 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
395 PN->eraseFromParent();
407 for (
SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
408 I = DeferredReplacements.begin(),
409 E = DeferredReplacements.end();
411 I->first->replaceAllUsesWith(
I->second);
412 I->first->eraseFromParent();
438 llvm::PointerType *PointerTy =
Int8PtrTy;
439 llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
440 llvm::FunctionType *FunctionTy =
441 llvm::FunctionType::get(
VoidTy, ProfileFuncArgs,
false);
444 llvm::CallInst *CallSite =
Builder.CreateCall(
446 llvm::ConstantInt::get(
Int32Ty, 0),
450 llvm::ConstantExpr::getBitCast(
CurFn, PointerTy),
458 std::string ReadOnlyQual(
"__read_only");
459 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
460 if (ReadOnlyPos != std::string::npos)
462 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
464 std::string WriteOnlyQual(
"__write_only");
465 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
466 if (WriteOnlyPos != std::string::npos)
467 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
469 std::string ReadWriteQual(
"__read_write");
470 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
471 if (ReadWritePos != std::string::npos)
472 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
524 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
527 std::string typeQuals;
533 addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
537 std::string typeName =
541 std::string::size_type pos = typeName.find(
"unsigned");
542 if (pointeeTy.
isCanonical() && pos != std::string::npos)
543 typeName.erase(pos+1, 8);
545 argTypeNames.push_back(llvm::MDString::get(Context, typeName));
547 std::string baseTypeName =
553 pos = baseTypeName.find(
"unsigned");
554 if (pos != std::string::npos)
555 baseTypeName.erase(pos+1, 8);
557 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
561 typeQuals =
"restrict";
564 typeQuals += typeQuals.empty() ?
"const" :
" const";
566 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
568 uint32_t AddrSpc = 0;
573 addressQuals.push_back(
574 llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
577 std::string typeName;
580 .getAsString(Policy);
585 std::string::size_type pos = typeName.find(
"unsigned");
587 typeName.erase(pos+1, 8);
589 std::string baseTypeName;
592 ->getElementType().getCanonicalType()
593 .getAsString(Policy);
607 argTypeNames.push_back(llvm::MDString::get(Context, typeName));
610 pos = baseTypeName.find(
"unsigned");
611 if (pos != std::string::npos)
612 baseTypeName.erase(pos+1, 8);
614 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
620 argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
624 const OpenCLAccessAttr *A = parm->
getAttr<OpenCLAccessAttr>();
625 if (A && A->isWriteOnly())
626 accessQuals.push_back(llvm::MDString::get(Context,
"write_only"));
627 else if (A && A->isReadWrite())
628 accessQuals.push_back(llvm::MDString::get(Context,
"read_write"));
630 accessQuals.push_back(llvm::MDString::get(Context,
"read_only"));
632 accessQuals.push_back(llvm::MDString::get(Context,
"none"));
635 argNames.push_back(llvm::MDString::get(Context, parm->
getName()));
638 Fn->setMetadata(
"kernel_arg_addr_space",
639 llvm::MDNode::get(Context, addressQuals));
640 Fn->setMetadata(
"kernel_arg_access_qual",
641 llvm::MDNode::get(Context, accessQuals));
642 Fn->setMetadata(
"kernel_arg_type",
643 llvm::MDNode::get(Context, argTypeNames));
644 Fn->setMetadata(
"kernel_arg_base_type",
645 llvm::MDNode::get(Context, argBaseTypeNames));
646 Fn->setMetadata(
"kernel_arg_type_qual",
647 llvm::MDNode::get(Context, argTypeQuals));
649 Fn->setMetadata(
"kernel_arg_name",
650 llvm::MDNode::get(Context, argNames));
653 void CodeGenFunction::EmitOpenCLKernelMetadata(
const FunctionDecl *FD,
656 if (!FD->
hasAttr<OpenCLKernelAttr>())
663 if (
const VecTypeHintAttr *A = FD->
getAttr<VecTypeHintAttr>()) {
664 QualType HintQTy = A->getTypeHint();
666 bool IsSignedInteger =
669 llvm::Metadata *AttrMDArgs[] = {
670 llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
672 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
673 llvm::IntegerType::get(Context, 32),
674 llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
675 Fn->setMetadata(
"vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
678 if (
const WorkGroupSizeHintAttr *A = FD->
getAttr<WorkGroupSizeHintAttr>()) {
679 llvm::Metadata *AttrMDArgs[] = {
680 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getXDim())),
681 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getYDim())),
682 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getZDim()))};
683 Fn->setMetadata(
"work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
686 if (
const ReqdWorkGroupSizeAttr *A = FD->
getAttr<ReqdWorkGroupSizeAttr>()) {
687 llvm::Metadata *AttrMDArgs[] = {
688 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getXDim())),
689 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getYDim())),
690 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getZDim()))};
691 Fn->setMetadata(
"reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
694 if (
const OpenCLIntelReqdSubGroupSizeAttr *A =
695 FD->
getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
696 llvm::Metadata *AttrMDArgs[] = {
697 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getSubGroupSize()))};
698 Fn->setMetadata(
"intel_reqd_sub_group_size",
699 llvm::MDNode::get(Context, AttrMDArgs));
705 const Stmt *Body =
nullptr;
706 if (
auto *FD = dyn_cast_or_null<FunctionDecl>(F))
708 else if (
auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
709 Body = OMD->getBody();
711 if (
auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
712 auto LastStmt = CS->body_rbegin();
713 if (LastStmt != CS->body_rend())
714 return isa<ReturnStmt>(*LastStmt);
720 Fn->addFnAttr(
"sanitize_thread_no_checking_at_run_time");
721 Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
732 "Do not use a CodeGenFunction object for more than one function");
736 DidCallStackSave =
false;
738 if (
const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
745 assert(
CurFn->isDeclaration() &&
"Function already has body?");
757 if (
SanOpts.
hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
758 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
760 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
762 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
764 Fn->addFnAttr(llvm::Attribute::SafeStack);
769 if (
const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
770 IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
773 (OMD->getSelector().isUnarySelector() && II->
isStr(
".cxx_destruct"))) {
776 }
else if (
const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
778 if (II && II->
isStr(
"__destroy_helper_block_"))
785 if (
const auto *XRayAttr = D->
getAttr<XRayInstrumentAttr>()) {
786 if (XRayAttr->alwaysXRayInstrument())
787 Fn->addFnAttr(
"function-instrument",
"xray-always");
788 if (XRayAttr->neverXRayInstrument())
789 Fn->addFnAttr(
"function-instrument",
"xray-never");
790 if (
const auto *LogArgs = D->
getAttr<XRayLogArgsAttr>()) {
791 Fn->addFnAttr(
"xray-log-args",
792 llvm::utostr(LogArgs->getArgumentCount()));
797 "xray-instruction-threshold",
802 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
807 Fn->addFnAttr(
"no-jump-tables",
812 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
813 EmitOpenCLKernelMetadata(FD, Fn);
819 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
820 if (llvm::Constant *PrologueSig =
822 llvm::Constant *FTRTTIConst =
824 llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
825 llvm::Constant *PrologueStructConst =
826 llvm::ConstantStruct::getAnon(PrologueStructElems,
true);
827 Fn->setPrologueData(PrologueStructConst);
834 if (
SanOpts.
has(SanitizerKind::NullabilityReturn)) {
837 if (!(
SanOpts.
has(SanitizerKind::ReturnsNonnullAttribute) &&
839 RetValNullabilityPrecondition =
848 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
850 Fn->addFnAttr(llvm::Attribute::NoRecurse);
862 Builder.SetInsertPoint(EntryBB);
866 if (requiresReturnValueCheck()) {
877 if (
auto *FD = dyn_cast_or_null<FunctionDecl>(D))
879 CC = SrcFnTy->getCallConv();
882 ArgTypes.push_back(VD->getType());
885 DI->EmitFunctionStart(GD, Loc, StartLoc, FnType,
CurFn,
Builder);
897 Fn->addFnAttr(
"fentry-call",
"true");
900 Fn->addFnAttr(
"counting-function",
getTarget().getMCountName());
915 auto AI =
CurFn->arg_begin();
923 llvm::Function::arg_iterator EI =
CurFn->arg_end();
945 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
972 if (FD->hasCapturedVLAType()) {
975 auto VAT = FD->getCapturedVLAType();
976 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
983 CXXThisValue = CXXABIThisValue;
987 if (CXXABIThisValue) {
989 SkippedChecks.
set(SanitizerKind::ObjectSize,
true);
996 cast<CXXRecordDecl>(MD->
getParent())->getLambdaCaptureDefault() ==
998 SkippedChecks.
set(SanitizerKind::Null,
true);
1002 Loc, CXXABIThisValue, ThisTy,
1010 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1018 if (
const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1019 Ty = PVD->getOriginalType();
1028 DI->EmitLocation(
Builder, StartLoc);
1046 llvm::BasicBlock *SkipCountBB =
nullptr;
1068 if (F->isInterposable())
return;
1070 for (llvm::BasicBlock &BB : *F)
1071 for (llvm::Instruction &
I : BB)
1075 F->setDoesNotThrow();
1095 bool PassedParams =
true;
1097 if (
auto Inherited = CD->getInheritedConstructor())
1103 Args.push_back(Param);
1104 if (!Param->hasAttr<PassObjectSizeAttr>())
1108 getContext(), Param->getDeclContext(), Param->getLocation(),
1110 SizeArguments[Param] = Implicit;
1111 Args.push_back(Implicit);
1115 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1128 if (
const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1129 return !ClassDecl->hasTrivialDestructor();
1143 if (FD->
hasAttr<NoDebugAttr>())
1144 DebugInfo =
nullptr;
1150 BodyRange = Body->getSourceRange();
1153 CurEHLocation = BodyRange.
getEnd();
1165 if (SpecDecl->hasBody(SpecDecl))
1166 Loc = SpecDecl->getLocation();
1172 if (Body && ShouldEmitLifetimeMarkers)
1180 if (isa<CXXDestructorDecl>(FD))
1182 else if (isa<CXXConstructorDecl>(FD))
1186 FD->
hasAttr<CUDAGlobalAttr>())
1188 else if (isa<CXXConversionDecl>(FD) &&
1189 cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
1193 }
else if (isa<CXXMethodDecl>(FD) &&
1194 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1198 }
else if (FD->
isDefaulted() && isa<CXXMethodDecl>(FD) &&
1199 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1200 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1207 llvm_unreachable(
"no definition for emitted function");
1217 bool ShouldEmitUnreachable =
1223 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1224 SanitizerHandler::MissingReturn,
1226 }
else if (ShouldEmitUnreachable) {
1230 if (
SanOpts.
has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1232 Builder.ClearInsertionPoint();
1241 if (!
CurFn->doesNotThrow())
1250 if (!S)
return false;
1257 if (isa<LabelStmt>(S))
1262 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1266 if (isa<SwitchStmt>(S))
1267 IgnoreCaseStmts =
true;
1282 if (!S)
return false;
1286 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1290 if (isa<BreakStmt>(S))
1302 if (!S)
return false;
1308 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1309 isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1310 isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1311 isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1314 if (isa<DeclStmt>(S))
1330 llvm::APSInt ResultInt;
1334 ResultBool = ResultInt.getBoolValue();
1342 llvm::APSInt &ResultInt,
1364 llvm::BasicBlock *TrueBlock,
1365 llvm::BasicBlock *FalseBlock,
1366 uint64_t TrueCount) {
1369 if (
const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1372 if (CondBOp->getOpcode() == BO_LAnd) {
1375 bool ConstantBool =
false;
1418 if (CondBOp->getOpcode() == BO_LOr) {
1421 bool ConstantBool =
false;
1447 uint64_t RHSCount = TrueCount - LHSCount;
1469 if (
const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1471 if (CondUOp->getOpcode() == UO_LNot) {
1494 uint64_t LHSScaledTrueCount = 0;
1498 LHSScaledTrueCount = TrueCount * LHSRatio;
1507 LHSScaledTrueCount);
1514 TrueCount - LHSScaledTrueCount);
1520 if (
const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1533 llvm::MDNode *Unpredictable =
nullptr;
1534 auto *Call = dyn_cast<
CallExpr>(Cond);
1536 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1537 if (FD && FD->
getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1539 Unpredictable = MDHelper.createUnpredictable();
1546 llvm::MDNode *Weights =
1547 createProfileWeights(TrueCount, CurrentCount - TrueCount);
1555 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1583 Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars,
"vla.end");
1585 llvm::BasicBlock *originBB = CGF.
Builder.GetInsertBlock();
1593 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2,
"vla.cur");
1594 cur->addIncoming(begin.getPointer(), originBB);
1605 Builder.CreateInBoundsGEP(CGF.
Int8Ty, cur, baseSizeInChars,
"vla.next");
1608 llvm::Value *done = Builder.CreateICmpEQ(next, end,
"vla-init.isdone");
1609 Builder.CreateCondBr(done, contBB, loopBB);
1610 cur->addIncoming(next, loopBB);
1620 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1639 dyn_cast_or_null<VariableArrayType>(
1643 std::tie(numElts, eltType) =
getVLASize(vlaType);
1647 if (!eltSize.
isOne())
1668 llvm::GlobalVariable *NullVariable =
1669 new llvm::GlobalVariable(
CGM.
getModule(), NullConstant->getType(),
1671 llvm::GlobalVariable::PrivateLinkage,
1672 NullConstant, Twine());
1674 NullVariable->setAlignment(NullAlign.getQuantity());
1693 if (!IndirectBranch)
1699 IndirectBranch->addDestination(BB);
1700 return llvm::BlockAddress::get(
CurFn, BB);
1705 if (IndirectBranch)
return IndirectBranch->getParent();
1711 "indirect.goto.dest");
1714 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1715 return IndirectBranch->getParent();
1723 const ArrayType *arrayType = origArrayType;
1728 if (isa<VariableArrayType>(arrayType)) {
1729 numVLAElements =
getVLASize(cast<VariableArrayType>(arrayType)).first;
1739 baseType = elementType;
1740 return numVLAElements;
1742 }
while (isa<VariableArrayType>(arrayType));
1754 llvm::ConstantInt *zero =
Builder.getInt32(0);
1755 gepIndices.push_back(zero);
1757 uint64_t countFromCLAs = 1;
1760 llvm::ArrayType *llvmArrayType =
1762 while (llvmArrayType) {
1763 assert(isa<ConstantArrayType>(arrayType));
1764 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1765 == llvmArrayType->getNumElements());
1767 gepIndices.push_back(zero);
1768 countFromCLAs *= llvmArrayType->getNumElements();
1772 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1774 assert((!llvmArrayType || arrayType) &&
1775 "LLVM and Clang types are out-of-synch");
1784 cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1794 gepIndices,
"array.begin"),
1801 = llvm::ConstantInt::get(
SizeTy, countFromCLAs);
1805 numElements =
Builder.CreateNUWMul(numVLAElements, numElements);
1810 std::pair<llvm::Value*, QualType>
1813 assert(vla &&
"type was not a variable array type!");
1817 std::pair<llvm::Value*, QualType>
1826 assert(vlaSize &&
"no size for VLA!");
1827 assert(vlaSize->getType() ==
SizeTy);
1830 numElements = vlaSize;
1834 numElements =
Builder.CreateNUWMul(numElements, vlaSize);
1836 }
while ((type =
getContext().getAsVariableArrayType(elementType)));
1838 return std::pair<llvm::Value*,QualType>(numElements, elementType);
1843 "Must pass variably modified type to EmitVLASizes!");
1853 switch (ty->getTypeClass()) {
1855 #define TYPE(Class, Base)
1856 #define ABSTRACT_TYPE(Class, Base)
1857 #define NON_CANONICAL_TYPE(Class, Base)
1858 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1859 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1860 #include "clang/AST/TypeNodes.def"
1861 llvm_unreachable(
"unexpected dependent type!");
1867 case Type::ExtVector:
1870 case Type::Elaborated:
1871 case Type::TemplateSpecialization:
1872 case Type::ObjCTypeParam:
1873 case Type::ObjCObject:
1874 case Type::ObjCInterface:
1875 case Type::ObjCObjectPointer:
1876 llvm_unreachable(
"type class is never variably-modified!");
1878 case Type::Adjusted:
1879 type = cast<AdjustedType>(ty)->getAdjustedType();
1883 type = cast<DecayedType>(ty)->getPointeeType();
1887 type = cast<PointerType>(ty)->getPointeeType();
1890 case Type::BlockPointer:
1891 type = cast<BlockPointerType>(ty)->getPointeeType();
1894 case Type::LValueReference:
1895 case Type::RValueReference:
1896 type = cast<ReferenceType>(ty)->getPointeeType();
1899 case Type::MemberPointer:
1900 type = cast<MemberPointerType>(ty)->getPointeeType();
1903 case Type::ConstantArray:
1904 case Type::IncompleteArray:
1906 type = cast<ArrayType>(ty)->getElementType();
1909 case Type::VariableArray: {
1927 size->getType()->isSignedIntegerType()) {
1929 llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1930 llvm::Constant *StaticArgs[] = {
1935 SanitizerKind::VLABound),
1936 SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
1948 case Type::FunctionProto:
1949 case Type::FunctionNoProto:
1950 type = cast<FunctionType>(ty)->getReturnType();
1955 case Type::UnaryTransform:
1956 case Type::Attributed:
1957 case Type::SubstTemplateTypeParm:
1958 case Type::PackExpansion:
1964 case Type::Decltype:
1966 case Type::DeducedTemplateSpecialization:
1970 case Type::TypeOfExpr:
1976 type = cast<AtomicType>(ty)->getValueType();
1980 type = cast<PipeType>(ty)->getElementType();
1987 if (
getContext().getBuiltinVaListType()->isArrayType())
1998 assert(!Init.
isUninit() &&
"Invalid DeclRefExpr initializer!");
2001 Dbg->EmitGlobalVariable(E->
getDecl(), Init);
2016 llvm::Instruction *inst =
new llvm::BitCastInst(value, value->getType(),
"",
2020 protection.Inst = inst;
2025 if (!protection.Inst)
return;
2028 protection.Inst->eraseFromParent();
2033 StringRef AnnotationStr,
2041 return Builder.CreateCall(AnnotationFn, Args);
2045 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
2056 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
2084 CGF->IsSanitizerScope =
false;
2088 const llvm::Twine &
Name,
2089 llvm::BasicBlock *BB,
2090 llvm::BasicBlock::iterator InsertPt)
const {
2097 llvm::Instruction *
I,
const llvm::Twine &
Name, llvm::BasicBlock *BB,
2098 llvm::BasicBlock::iterator InsertPt)
const {
2099 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
2101 CGF->InsertHelper(I, Name, BB, InsertPt);
2106 std::string &FirstMissing) {
2108 if (ReqFeatures.empty())
2113 llvm::StringMap<bool> CallerFeatureMap;
2119 ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
2121 Feature.split(OrFeatures,
"|");
2122 return std::any_of(OrFeatures.begin(), OrFeatures.end(),
2123 [&](StringRef Feature) {
2124 if (!CallerFeatureMap.lookup(Feature)) {
2125 FirstMissing = Feature.str();
2151 std::string MissingFeature;
2154 const char *FeatureList =
2157 if (!FeatureList || StringRef(FeatureList) ==
"")
2159 StringRef(FeatureList).split(ReqFeatures,
",");
2165 }
else if (TargetDecl->
hasAttr<TargetAttr>()) {
2168 llvm::StringMap<bool> CalleeFeatureMap;
2170 for (
const auto &F : CalleeFeatureMap) {
2173 ReqFeatures.push_back(F.getKey());
2185 llvm::IRBuilder<> IRB(
Builder.GetInsertBlock(),
Builder.GetInsertPoint());
2186 IRB.SetCurrentDebugLocation(
Builder.getCurrentDebugLocation());
2192 return DI->SourceLocToDebugLoc(Location);
2194 return llvm::DebugLoc();
unsigned getAddressSpace() const
Return the address space of this type.
Defines the clang::ASTContext interface.
SourceLocation getEnd() const
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T)
Given a value of type T* that may not be to a complete object, construct an l-value with the natural ...
void end(CodeGenFunction &CGF)
Parameter for captured context.
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
A (possibly-)qualified type.
CodeGenTypes & getTypes()
llvm::Type * ConvertTypeForMem(QualType T)
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
CanQualType getReturnType() const
CXXCtorType getCtorType() const
unsigned getInAllocaFieldIndex() const
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler...
llvm::Module & getModule() const
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
void EmitFunctionInstrumentation(const char *Fn)
EmitFunctionInstrumentation - Emit LLVM code to call the specified instrumentation function with the ...
bool isOne() const
isOne - Test whether the quantity equals one.
virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, FunctionArgList &Params)=0
Insert any ABI-specific implicit parameters into the parameter list for a function.
CharUnits getClassPointerAlignment(const CXXRecordDecl *CD)
Returns the assumed alignment of an opaque pointer to the given class.
Stmt - This represents one statement.
FunctionType - C99 6.7.5.3 - Function Declarators.
const TargetInfo & getTarget() const
SanitizerSet Sanitize
Set of enabled sanitizers.
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
static bool endsWithReturn(const Decl *F)
Determine whether the function F ends with a return stmt.
Checking the 'this' pointer for a constructor call.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Decl - This represents one declaration (or definition), e.g.
Address getAddress() const
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, QualType Type, CharUnits Alignment=CharUnits::Zero(), SanitizerSet SkippedChecks=SanitizerSet())
Emit a check that V is the address of storage of the appropriate size and alignment for an object of ...
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, llvm::BasicBlock::iterator InsertPt) const
This forwards to CodeGenFunction::InsertHelper.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
static void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn)
std::string getAsString() const
The base class of the type hierarchy.
bool ShouldInstrumentFunction()
ShouldInstrumentFunction - Return true if the current function should be instrumented with __cyg_prof...
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
Represents an array type, per C99 6.7.5.2 - Array Declarators.
static bool hasRequiredFeatures(const SmallVectorImpl< StringRef > &ReqFeatures, CodeGenModule &CGM, const FunctionDecl *FD, std::string &FirstMissing)
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, bool forPointeeType=false)
const LangOptions & getLangOpts() const
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Represents a C++ constructor within a class.
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant, or if it does but contains a label, return false.
This file provides some common utility functions for processing Lambda related AST Constructs...
TypeEvaluationKind
The kind of evaluation to perform on values of a particular type.
VarDecl - An instance of this class is created to represent a variable declaration or definition...
llvm::Type * getElementType() const
Return the type of the values stored in this address.
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
Extra information about a function prototype.
static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts, const LangOptions &LangOpts)
shouldEmitLifetimeMarkers - Decide whether we need emit the life-time markers.
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
QualType getThisType(ASTContext &C) const
Returns the type of the this pointer.
static bool mightAddDeclToScope(const Stmt *S)
Determine if the given statement might introduce a declaration into the current scope, by being a (possibly-labelled) DeclStmt.
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID)
Emit a call to trap or debugtrap and attach function attribute "trap-func-name" if specified...
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
void setCurrentProfileCount(uint64_t Count)
Set the profiler's current count.
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
Describes how types, statements, expressions, and declarations should be printed. ...
Defines the Objective-C statement AST node classes.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
A C++ throw-expression (C++ [except.throw]).
ParmVarDecl - Represents a parameter to a function.
bool isObjCRetainableType() const
static void destroyBlockInfos(CGBlockInfo *info)
Destroy a chain of block layouts.
void emitImplicitAssignmentOperatorBody(FunctionArgList &Args)
EHScopeStack::stable_iterator PrologueCleanupDepth
PrologueCleanupDepth - The cleanup depth enclosing all the cleanups associated with the parameters...
virtual bool hasMostDerivedReturn(GlobalDecl GD) const
JumpDest getJumpDestForLabel(const LabelDecl *S)
getBasicBlockForLabel - Return the LLVM basicblock that the specified label maps to.
llvm::DenseMap< const VarDecl *, FieldDecl * > LambdaCaptureFields
An object to manage conditionally-evaluated expressions.
PeepholeProtection protectFromPeepholes(RValue rvalue)
protectFromPeepholes - Protect a value that we're intending to store to the side, but which will prob...
bool ShouldXRayInstrumentFunction() const
ShouldXRayInstrument - Return true if the current function should be instrumented with XRay nop sleds...
One of these records is kept for each identifier that is lexed.
CGBlockInfo * FirstBlockInfo
FirstBlockInfo - The head of a singly-linked-list of block layouts.
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerMask >> Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs)
Create a basic block that will call a handler function in a sanitizer runtime with the provided argum...
void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, SourceLocation EndLoc)
EmitFunctionEpilog - Emit the target specific LLVM code to return the given temporary.
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
CGDebugInfo * getDebugInfo()
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
Expr * getSizeExpr() const
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
LValue EmitLValueForLambdaField(const FieldDecl *Field)
Given that we are currently emitting a lambda, emit an l-value for one of its members.
QualType getReturnType() const
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
llvm::IntegerType * SizeTy
const FunctionDecl * CurSEHParent
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, llvm::BasicBlock::iterator InsertPt) const
CGBuilder insert helper.
SanitizerMask Mask
Bitmask of enabled sanitizers.
bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, StringRef Category=StringRef()) const
Imbue XRay attributes to a function, applying the always/never attribute lists in the process...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
void InitTempAlloca(Address Alloca, llvm::Value *Value)
InitTempAlloca - Provide an initial value for the given alloca which will be observable at all locati...
const Decl * getDecl() const
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
Address CreateIRTemp(QualType T, const Twine &Name="tmp")
CreateIRTemp - Create a temporary IR object of the given type, with appropriate alignment.
virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF)=0
Emit the ABI-specific prolog for the function.
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr)
static bool hasScalarEvaluationKind(QualType T)
Address CreateElementBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Cast the element type of the given address to a different type, preserving information like the align...
CharUnits - This is an opaque type for sizes expressed in character units.
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
bool isDefaulted() const
Whether this function is defaulted per C++0x.
virtual llvm::Constant * getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const
Return a constant used by UBSan as a signature to identify functions possessing type information...
field_range fields() const
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
A builtin binary operation expression such as "x + y" or "x <= y".
The l-value was considered opaque, so the alignment was determined from a type, but that type was an ...
FunctionDecl * getTemplateInstantiationPattern() const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Values of this type can never be null.
static unsigned ArgInfoAddressSpace(unsigned LangAS)
void EmitStmt(const Stmt *S)
EmitStmt - Emit the code for the statement.
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
void assignRegionCounters(GlobalDecl GD, llvm::Function *Fn)
Assign counters to regions and configure them for PGO of a given function.
TypeClass getTypeClass() const
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
llvm::SanitizerStatReport & getSanStats()
llvm::DebugLoc EmitReturnBlock()
Emit the unified return block, trying to avoid its emission when possible.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
uint64_t getCurrentProfileCount()
Get the profiler's current count.
detail::InMemoryDirectory::const_iterator I
virtual void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args)=0
Emits a kernel launch stub.
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
static void removeImageAccessQualifier(std::string &TyName)
void begin(CodeGenFunction &CGF)
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create a new runtime function with the specified type and name.
Checking the 'this' pointer for a call to a non-static member function.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
ConditionalOperator - The ?: ternary operator.
static CharUnits One()
One - Construct a CharUnits quantity of one.
CompoundStmt - This represents a group of statements like { stmt stmt }.
llvm::CallInst * EmitNounwindRuntimeCall(llvm::Value *callee, const Twine &name="")
const TargetCodeGenInfo & getTargetCodeGenInfo()
RValue - This trivial value class is used to represent the result of an expression that is evaluated...
void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK)
static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB)
bool usesSEHTry() const
Indicates the function uses __try.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Address CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
bool hasUnaligned() const
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *FD)
static TypeEvaluationKind getEvaluationKind(QualType T)
hasAggregateLLVMType - Return true if the specified AST type will map into an aggregate LLVM type or ...
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
llvm::Value * getPointer() const
llvm::BasicBlock * EHResumeBlock
EHResumeBlock - Unified block containing a call to llvm.eh.resume.
bool empty() const
Determines whether the exception-scopes stack is empty.
Expr - This represents one expression.
Emit only debug info necessary for generating line number tables (-gline-tables-only).
CGCXXABI & getCXXABI() const
CharUnits getIndirectAlign() const
const ParmVarDecl * getParamDecl(unsigned i) const
static void TryMarkNoThrow(llvm::Function *F)
Tries to mark the given function nounwind based on the non-existence of any throwing calls within it...
ASTContext & getContext() const
llvm::BasicBlock * getBlock() const
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
void clear(SanitizerMask K=SanitizerKind::All)
Disable the sanitizers specified in K.
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
llvm::LLVMContext & getLLVMContext()
llvm::BasicBlock * GetIndirectGotoBlock()
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
llvm::IntegerType * Int32Ty
void EmitConstructorBody(FunctionArgList &Args)
EmitConstructorBody - Emits the body of the current constructor.
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
virtual bool HasThisReturn(GlobalDecl GD) const
Returns true if the given constructor or destructor is one of the kinds that the ABI says returns 'th...
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T)
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
bool containsOnlyLifetimeMarkers(stable_iterator Old) const
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
An object which temporarily prevents a value from being destroyed by aggressive peephole optimization...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
void EmitLambdaToBlockPointerBody(FunctionArgList &Args)
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys=None)
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
QualType getElementType() const
virtual void startNewFunction()
CallingConv
CallingConv - Specifies the calling convention that a function uses.
GlobalDecl - represents a global declaration.
const clang::PrintingPolicy & getPrintingPolicy() const
SanitizerScope(CodeGenFunction *CGF)
VarBypassDetector Bypasses
The l-value was considered opaque, so the alignment was determined from a type.
Stmt * getBody(const FunctionDecl *&Definition) const
getBody - Retrieve the body (definition) of the function.
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
bool SawAsmBlock
Whether we processed a Microsoft-style asm block during CodeGen.
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.
ASTContext & getContext() const
Encodes a location in the source.
CharUnits getPointerAlign() const
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go...
unsigned getNumParams() const
getNumParams - Return the number of parameters this function must have based on its FunctionType...
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
bool inheritingCtorHasParams(const InheritedConstructor &Inherited, CXXCtorType Type)
Determine if a C++ inheriting constructor should have parameters matching those of its inherited cons...
const char * getRequiredFeatures(unsigned ID) const
LabelDecl - Represents the declaration of a label.
A scoped helper to set the current debug location to the specified location or preferred location of ...
Represents a static or instance method of a struct/union/class.
bool isReturnsRetained() const
In ARC, whether this function retains its return value.
ArrayRef< ParmVarDecl * > parameters() const
SanitizerSet SanOpts
Sanitizers enabled for this function.
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
const CodeGenOptions & getCodeGenOpts() const
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, std::initializer_list< llvm::Value ** > ValuesToReload={})
Takes the old cleanup stack size and emits the cleanup blocks that have been added.
const LangOptions & getLangOpts() const
SourceLocation getBegin() const
MangleContext & getMangleContext()
Gets the mangle context.
void getCaptureFields(llvm::DenseMap< const VarDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
InAlloca - Pass the argument directly using the LLVM inalloca attribute.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Address EmitMSVAListRef(const Expr *E)
Emit a "reference" to a __builtin_ms_va_list; this is always the value of the expression, because a __builtin_ms_va_list is a pointer to a char.
const CGFunctionInfo * CurFnInfo
void EmitStartEHSpec(const Decl *D)
EmitStartEHSpec - Emit the start of the exception spec.
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
This is an IRBuilder insertion helper that forwards to CodeGenFunction::InsertHelper, which adds necessary metadata to instructions.
Address EmitVAListRef(const Expr *E)
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type, returning the result.
bool isSRetAfterThis() const
FunctionArgList - Type for representing both the decl and type of parameters to a function...
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
CGFunctionInfo - Class to encapsulate the information about a function definition.
CharUnits getAlignment() const
Return the alignment of this pointer.
This class organizes the cross-function state that is used while generating LLVM code.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init)
static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, Address dest, Address src, llvm::Value *sizeInChars)
emitNonZeroVLAInit - Emit the "zero" initialization of a variable-length array whose elements have a ...
Address EmitFieldAnnotations(const FieldDecl *D, Address V)
Emit field annotations for the given field & value.
void Init(const Stmt *Body)
Clear the object and pre-process for the given statement, usually function body statement.
bool isZero() const
isZero - Test whether the quantity equals zero.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
virtual ~CGCapturedStmtInfo()
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Address CreateStructGEP(Address Addr, unsigned Index, CharUnits Offset, const llvm::Twine &Name="")
llvm::Value * EmitAnnotationCall(llvm::Value *AnnotationFn, llvm::Value *AnnotatedVal, StringRef AnnotationStr, SourceLocation Location)
Emit an annotation call (intrinsic or builtin).
llvm::LoadInst * CreateAlignedLoad(llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
llvm::IntegerType * IntPtrTy
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks, lambdas, etc.
static LValue MakeAddr(Address address, QualType type, ASTContext &Context, LValueBaseInfo BaseInfo, llvm::MDNode *TBAAInfo=nullptr)
void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params)
Build a parameter variable suitable for 'this'.
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
detail::InMemoryDirectory::const_iterator E
llvm::SmallVector< char, 256 > LifetimeExtendedCleanupStack
bool isLambda() const
Determine whether this class describes a lambda function object.
bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const
static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn, CodeGenModule &CGM, llvm::LLVMContext &Context, CGBuilderTy &Builder, ASTContext &ASTCtx)
const VariableArrayType * getAsVariableArrayType(QualType T) const
JumpDest ReturnBlock
ReturnBlock - Unified return block.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S)
When instrumenting to collect profile data, the counts for some blocks such as switch cases need to n...
llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location)
Converts Location to a DebugLoc, if debug information is enabled.
const T * getAs() const
Member-template getAs<specific type>'.
QualType getCanonicalType() const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
llvm::PointerType * Int8PtrTy
void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD)
SourceLocation getLocStart() const LLVM_READONLY
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
ExtVectorType - Extended vector type.
QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args)
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl)
FieldDecl * LambdaThisCaptureField
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
ABIArgInfo & getReturnInfo()
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body)
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
void InsertHelper(llvm::Instruction *I) const
Function called by the CodeGenFunction when an instruction is created.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
void unprotectFromPeepholes(PeepholeProtection protection)
DiagnosticsEngine & getDiags() const
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet...
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Represents a C++ struct/union/class.
BoundNodesTreeBuilder *const Builder
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block, taking care to avoid creation of branches from dummy blocks.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
llvm::Type * ConvertType(QualType T)
void EmitFunctionProlog(const CGFunctionInfo &FI, llvm::Function *Fn, const FunctionArgList &Args)
EmitFunctionProlog - Emit the target specific LLVM code to load the arguments for the given function...
LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo=LValueBaseInfo(AlignmentSource::Type))
LValue EmitLValue(const Expr *E)
EmitLValue - Emit code to compute a designator that specifies the location of the expression...
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
Builtin::Context & BuiltinInfo
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
std::pair< llvm::Value *, QualType > getVLASize(const VariableArrayType *vla)
getVLASize - Returns an LLVM value that corresponds to the size, in non-variably-sized elements...
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
llvm::MDNode * getTBAAInfo(QualType QTy)
A reference to a declared variable, function, enum, etc.
static bool shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD, const ASTContext &Context)
void EmitDestructorBody(FunctionArgList &Args)
EmitDestructorBody - Emits the body of the current destructor.
QualType getElementType() const
This structure provides a set of types that are commonly used during IR emission. ...
void EmitEndEHSpec(const Decl *D)
EmitEndEHSpec - Emit the end of the exception spec.
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
CodeGenTypes & getTypes() const
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
LValue - This represents an lvalue references.
llvm::BlockAddress * GetAddrOfLabel(const LabelDecl *L)
void EmitVarAnnotations(const VarDecl *D, llvm::Value *V)
Emit local annotations for the local variable V, declared by D.
Represents a C array with a specified size that is not an integer-constant-expression.
SanitizerMetadata * getSanitizerMetadata()
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
bool isConstQualified() const
Determine whether this type is const-qualified.
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
llvm::Value * emitArrayLength(const ArrayType *arrayType, QualType &baseType, Address &addr)
emitArrayLength - Compute the length of an array, even if it's a VLA, and drill down to the base elem...
static bool containsBreak(const Stmt *S)
containsBreak - Return true if the statement contains a break out of it.
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
bool isZeroInitializable(QualType T)
IsZeroInitializable - Return whether a type can be zero-initialized (in the C++ sense) with an LLVM z...
Defines enum values for all the target-independent builtin functions.
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
Attr - This represents one attribute.
void EmitNullInitialization(Address DestPtr, QualType Ty)
EmitNullInitialization - Generate code to set a value of the given type to null, If the type contains...
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
bool isPointerType() const
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...