35 #include "llvm/IR/DataLayout.h" 36 #include "llvm/IR/Dominators.h" 37 #include "llvm/IR/Intrinsics.h" 38 #include "llvm/IR/MDBuilder.h" 39 #include "llvm/IR/Operator.h" 40 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 41 using namespace clang;
42 using namespace CodeGen;
48 if (CGOpts.DisableLifetimeMarkers)
57 if (CGOpts.SanitizeAddressUseAfterScope)
61 return CGOpts.OptimizationLevel != 0;
64 CodeGenFunction::CodeGenFunction(
CodeGenModule &cgm,
bool suppressNewContext)
66 Builder(cgm, cgm.getModule().getContext(),
llvm::ConstantFolder(),
68 CurFn(nullptr), ReturnValue(
Address::invalid()),
69 CapturedStmtInfo(nullptr), SanOpts(CGM.getLangOpts().Sanitize),
70 IsSanitizerScope(
false), CurFuncIsThunk(
false), AutoreleaseResult(
false),
71 SawAsmBlock(
false), IsOutlinedSEHHelper(
false), BlockInfo(nullptr),
72 BlockPointer(nullptr), LambdaThisCaptureField(nullptr),
73 NormalCleanupDest(nullptr), NextCleanupDestIndex(1),
74 FirstBlockInfo(nullptr), EHResumeBlock(nullptr), ExceptionSlot(nullptr),
75 EHSelectorSlot(nullptr), DebugInfo(CGM.getModuleDebugInfo()),
76 DisableDebugInfo(
false), DidCallStackSave(
false), IndirectBranch(nullptr),
77 PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
78 CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
79 NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
80 CXXABIThisValue(nullptr), CXXThisValue(nullptr),
81 CXXStructorImplicitParamDecl(nullptr),
82 CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
83 CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
84 TerminateHandler(nullptr), TrapBB(nullptr),
85 ShouldEmitLifetimeMarkers(
87 if (!suppressNewContext)
90 llvm::FastMathFlags FMF;
101 FMF.setNoSignedZeros();
104 FMF.setAllowReciprocal();
107 FMF.setAllowReassoc();
135 bool forPointeeType) {
143 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
171 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
212 #define TYPE(name, parent) 213 #define ABSTRACT_TYPE(name, parent) 214 #define NON_CANONICAL_TYPE(name, parent) case Type::name: 215 #define DEPENDENT_TYPE(name, parent) case Type::name: 216 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 217 #include "clang/AST/TypeNodes.def" 218 llvm_unreachable(
"non-canonical or dependent type in IR-generation");
221 case Type::DeducedTemplateSpecialization:
222 llvm_unreachable(
"undeduced type in IR-generation");
227 case Type::BlockPointer:
228 case Type::LValueReference:
229 case Type::RValueReference:
230 case Type::MemberPointer:
232 case Type::ExtVector:
233 case Type::FunctionProto:
234 case Type::FunctionNoProto:
236 case Type::ObjCObjectPointer:
245 case Type::ConstantArray:
246 case Type::IncompleteArray:
247 case Type::VariableArray:
249 case Type::ObjCObject:
250 case Type::ObjCInterface:
255 type = cast<AtomicType>(
type)->getValueType();
258 llvm_unreachable(
"unknown type kind!");
265 llvm::BasicBlock *CurBB =
Builder.GetInsertBlock();
268 assert(!CurBB->getTerminator() &&
"Unexpected terminated block.");
277 return llvm::DebugLoc();
284 llvm::BranchInst *BI =
286 if (BI && BI->isUnconditional() &&
290 llvm::DebugLoc Loc = BI->getDebugLoc();
291 Builder.SetInsertPoint(BI->getParent());
292 BI->eraseFromParent();
303 return llvm::DebugLoc();
308 if (!BB->use_empty())
309 return CGF.
CurFn->getBasicBlockList().push_back(BB);
314 assert(BreakContinueStack.empty() &&
315 "mismatched push/pop in break/continue stack!");
317 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
318 && NumSimpleReturnExprs == NumReturnExprs
333 if (OnlySimpleReturnStmts)
334 DI->EmitLocation(
Builder, LastStopPoint);
336 DI->EmitLocation(
Builder, EndLoc);
344 bool HasOnlyLifetimeMarkers =
346 bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
351 if (OnlySimpleReturnStmts)
352 DI->EmitLocation(
Builder, EndLoc);
362 CurFn->addFnAttr(
"instrument-function-exit",
"__cyg_profile_func_exit");
364 CurFn->addFnAttr(
"instrument-function-exit-inlined",
365 "__cyg_profile_func_exit");
379 "did not remove all scopes from cleanup stack!");
383 if (IndirectBranch) {
390 if (!EscapedLocals.empty()) {
394 EscapeArgs.resize(EscapedLocals.size());
395 for (
auto &Pair : EscapedLocals)
396 EscapeArgs[Pair.second] = Pair.first;
397 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
405 Ptr->eraseFromParent();
409 if (IndirectBranch) {
410 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
411 if (PN->getNumIncomingValues() == 0) {
412 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
413 PN->eraseFromParent();
422 for (
const auto &FuncletAndParent : TerminateFunclets)
428 for (
SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
429 I = DeferredReplacements.begin(),
430 E = DeferredReplacements.end();
432 I->first->replaceAllUsesWith(I->second);
433 I->first->eraseFromParent();
443 llvm::DominatorTree DT(*
CurFn);
475 llvm::Constant *Addr) {
483 auto *GV =
new llvm::GlobalVariable(
CGM.
getModule(), Addr->getType(),
485 llvm::GlobalValue::PrivateLinkage, Addr);
488 auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV,
IntPtrTy);
489 auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F,
IntPtrTy);
490 auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
493 : llvm::ConstantExpr::getTrunc(PCRelAsInt,
Int32Ty);
501 auto *FuncAsInt =
Builder.CreatePtrToInt(F,
IntPtrTy,
"func_addr.int");
502 auto *GOTAsInt =
Builder.CreateAdd(PCRelAsInt, FuncAsInt,
"global_addr.int");
511 std::string ReadOnlyQual(
"__read_only");
512 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
513 if (ReadOnlyPos != std::string::npos)
515 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
517 std::string WriteOnlyQual(
"__write_only");
518 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
519 if (WriteOnlyPos != std::string::npos)
520 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
522 std::string ReadWriteQual(
"__read_write");
523 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
524 if (ReadWritePos != std::string::npos)
525 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
577 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
580 std::string typeQuals;
586 addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
590 std::string typeName =
594 std::string::size_type pos = typeName.find(
"unsigned");
595 if (pointeeTy.
isCanonical() && pos != std::string::npos)
596 typeName.erase(pos+1, 8);
598 argTypeNames.push_back(llvm::MDString::get(Context, typeName));
600 std::string baseTypeName =
606 pos = baseTypeName.find(
"unsigned");
607 if (pos != std::string::npos)
608 baseTypeName.erase(pos+1, 8);
610 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
614 typeQuals =
"restrict";
617 typeQuals += typeQuals.empty() ?
"const" :
" const";
619 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
621 uint32_t AddrSpc = 0;
626 addressQuals.push_back(
627 llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
630 std::string typeName;
633 .getAsString(Policy);
638 std::string::size_type pos = typeName.find(
"unsigned");
640 typeName.erase(pos+1, 8);
642 std::string baseTypeName;
645 ->getElementType().getCanonicalType()
646 .getAsString(Policy);
660 argTypeNames.push_back(llvm::MDString::get(Context, typeName));
663 pos = baseTypeName.find(
"unsigned");
664 if (pos != std::string::npos)
665 baseTypeName.erase(pos+1, 8);
667 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
673 argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
677 const Decl *PDecl = parm;
678 if (
auto *TD = dyn_cast<TypedefType>(ty))
679 PDecl = TD->getDecl();
680 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
681 if (A && A->isWriteOnly())
682 accessQuals.push_back(llvm::MDString::get(Context,
"write_only"));
683 else if (A && A->isReadWrite())
684 accessQuals.push_back(llvm::MDString::get(Context,
"read_write"));
686 accessQuals.push_back(llvm::MDString::get(Context,
"read_only"));
688 accessQuals.push_back(llvm::MDString::get(Context,
"none"));
691 argNames.push_back(llvm::MDString::get(Context, parm->
getName()));
694 Fn->setMetadata(
"kernel_arg_addr_space",
695 llvm::MDNode::get(Context, addressQuals));
696 Fn->setMetadata(
"kernel_arg_access_qual",
697 llvm::MDNode::get(Context, accessQuals));
698 Fn->setMetadata(
"kernel_arg_type",
699 llvm::MDNode::get(Context, argTypeNames));
700 Fn->setMetadata(
"kernel_arg_base_type",
701 llvm::MDNode::get(Context, argBaseTypeNames));
702 Fn->setMetadata(
"kernel_arg_type_qual",
703 llvm::MDNode::get(Context, argTypeQuals));
705 Fn->setMetadata(
"kernel_arg_name",
706 llvm::MDNode::get(Context, argNames));
709 void CodeGenFunction::EmitOpenCLKernelMetadata(
const FunctionDecl *FD,
712 if (!FD->
hasAttr<OpenCLKernelAttr>())
719 if (
const VecTypeHintAttr *A = FD->
getAttr<VecTypeHintAttr>()) {
720 QualType HintQTy = A->getTypeHint();
722 bool IsSignedInteger =
725 llvm::Metadata *AttrMDArgs[] = {
726 llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
728 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
729 llvm::IntegerType::get(Context, 32),
730 llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
731 Fn->setMetadata(
"vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
734 if (
const WorkGroupSizeHintAttr *A = FD->
getAttr<WorkGroupSizeHintAttr>()) {
735 llvm::Metadata *AttrMDArgs[] = {
736 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getXDim())),
737 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getYDim())),
738 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getZDim()))};
739 Fn->setMetadata(
"work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
742 if (
const ReqdWorkGroupSizeAttr *A = FD->
getAttr<ReqdWorkGroupSizeAttr>()) {
743 llvm::Metadata *AttrMDArgs[] = {
744 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getXDim())),
745 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getYDim())),
746 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getZDim()))};
747 Fn->setMetadata(
"reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
750 if (
const OpenCLIntelReqdSubGroupSizeAttr *A =
751 FD->
getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
752 llvm::Metadata *AttrMDArgs[] = {
753 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getSubGroupSize()))};
754 Fn->setMetadata(
"intel_reqd_sub_group_size",
755 llvm::MDNode::get(Context, AttrMDArgs));
761 const Stmt *Body =
nullptr;
762 if (
auto *FD = dyn_cast_or_null<FunctionDecl>(F))
764 else if (
auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
765 Body = OMD->getBody();
767 if (
auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
768 auto LastStmt = CS->body_rbegin();
769 if (LastStmt != CS->body_rend())
770 return isa<ReturnStmt>(*LastStmt);
776 Fn->addFnAttr(
"sanitize_thread_no_checking_at_run_time");
777 Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
781 auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
782 if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
783 !MD->getDeclName().getAsIdentifierInfo()->isStr(
"allocate") ||
784 (MD->getNumParams() != 1 && MD->getNumParams() != 2))
787 if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.
getSizeType())
790 if (MD->getNumParams() == 2) {
791 auto *PT = MD->parameters()[1]->getType()->getAs<
PointerType>();
792 if (!PT || !PT->isVoidPointerType() ||
793 !PT->getPointeeType().isConstQualified())
803 if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
817 "Do not use a CodeGenFunction object for more than one function");
821 DidCallStackSave =
false;
823 if (
const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
830 assert(
CurFn->isDeclaration() &&
"Function already has body?");
835 #define SANITIZER(NAME, ID) \ 836 if (SanOpts.empty()) \ 838 if (SanOpts.has(SanitizerKind::ID)) \ 839 if (CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc)) \ 840 SanOpts.set(SanitizerKind::ID, false); 842 #include "clang/Basic/Sanitizers.def" 853 if (
SanOpts.
hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
854 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
856 Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
858 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
860 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
862 Fn->addFnAttr(llvm::Attribute::SafeStack);
867 if (
const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
868 IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
871 (OMD->getSelector().isUnarySelector() && II->
isStr(
".cxx_destruct"))) {
874 }
else if (
const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
876 if (II && II->
isStr(
"__destroy_helper_block_"))
884 if (D &&
SanOpts.
has(SanitizerKind::CFIUnrelatedCast)) {
891 if (
const auto *XRayAttr = D->
getAttr<XRayInstrumentAttr>()) {
892 if (XRayAttr->alwaysXRayInstrument())
893 Fn->addFnAttr(
"function-instrument",
"xray-always");
894 if (XRayAttr->neverXRayInstrument())
895 Fn->addFnAttr(
"function-instrument",
"xray-never");
896 if (
const auto *LogArgs = D->
getAttr<XRayLogArgsAttr>()) {
897 Fn->addFnAttr(
"xray-log-args",
898 llvm::utostr(LogArgs->getArgumentCount()));
903 "xray-instruction-threshold",
909 Fn->addFnAttr(
"no-jump-tables",
914 Fn->addFnAttr(
"profile-sample-accurate");
918 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
919 EmitOpenCLKernelMetadata(FD, Fn);
925 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
927 llvm::Constant *FTRTTIConst =
929 llvm::Constant *FTRTTIConstEncoded =
931 llvm::Constant *PrologueStructElems[] = {PrologueSig,
933 llvm::Constant *PrologueStructConst =
934 llvm::ConstantStruct::getAnon(PrologueStructElems,
true);
935 Fn->setPrologueData(PrologueStructConst);
942 if (
SanOpts.
has(SanitizerKind::NullabilityReturn)) {
945 if (!(
SanOpts.
has(SanitizerKind::ReturnsNonnullAttribute) &&
947 RetValNullabilityPrecondition =
956 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
958 Fn->addFnAttr(llvm::Attribute::NoRecurse);
970 Builder.SetInsertPoint(EntryBB);
974 if (requiresReturnValueCheck()) {
985 if (
auto *FD = dyn_cast_or_null<FunctionDecl>(D))
987 CC = SrcFnTy->getCallConv();
990 ArgTypes.push_back(VD->getType());
993 DI->EmitFunctionStart(GD, Loc, StartLoc, FnType,
CurFn,
Builder);
998 CurFn->addFnAttr(
"instrument-function-entry",
"__cyg_profile_func_enter");
1000 CurFn->addFnAttr(
"instrument-function-entry-inlined",
1001 "__cyg_profile_func_enter");
1003 CurFn->addFnAttr(
"instrument-function-entry-inlined",
1004 "__cyg_profile_func_enter_bare");
1013 Fn->addFnAttr(
"fentry-call",
"true");
1016 Fn->addFnAttr(
"instrument-function-entry-inlined",
1033 auto AI =
CurFn->arg_begin();
1041 llvm::Function::arg_iterator EI =
CurFn->arg_end();
1063 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
1090 if (FD->hasCapturedVLAType()) {
1093 auto VAT = FD->getCapturedVLAType();
1094 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1101 CXXThisValue = CXXABIThisValue;
1105 if (CXXABIThisValue) {
1107 SkippedChecks.
set(SanitizerKind::ObjectSize,
true);
1114 cast<CXXRecordDecl>(MD->
getParent())->getLambdaCaptureDefault() ==
1116 SkippedChecks.
set(SanitizerKind::Null,
true);
1120 Loc, CXXABIThisValue, ThisTy,
1128 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1136 if (
const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1137 Ty = PVD->getOriginalType();
1146 DI->EmitLocation(
Builder, StartLoc);
1152 if (
const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1164 llvm::BasicBlock *SkipCountBB =
nullptr;
1186 if (F->isInterposable())
return;
1188 for (llvm::BasicBlock &BB : *F)
1189 for (llvm::Instruction &I : BB)
1193 F->setDoesNotThrow();
1213 bool PassedParams =
true;
1215 if (
auto Inherited = CD->getInheritedConstructor())
1221 Args.push_back(Param);
1222 if (!Param->hasAttr<PassObjectSizeAttr>())
1226 getContext(), Param->getDeclContext(), Param->getLocation(),
1228 SizeArguments[Param] = Implicit;
1229 Args.push_back(Implicit);
1233 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1246 if (
const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1247 return !ClassDecl->hasTrivialDestructor();
1261 if (FD->
hasAttr<NoDebugAttr>())
1262 DebugInfo =
nullptr;
1268 BodyRange = Body->getSourceRange();
1271 CurEHLocation = BodyRange.
getEnd();
1283 if (SpecDecl->hasBody(SpecDecl))
1284 Loc = SpecDecl->getLocation();
1290 if (Body && ShouldEmitLifetimeMarkers)
1298 if (isa<CXXDestructorDecl>(FD))
1300 else if (isa<CXXConstructorDecl>(FD))
1304 FD->
hasAttr<CUDAGlobalAttr>())
1306 else if (isa<CXXMethodDecl>(FD) &&
1307 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1311 }
else if (FD->
isDefaulted() && isa<CXXMethodDecl>(FD) &&
1312 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1313 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1320 llvm_unreachable(
"no definition for emitted function");
1330 bool ShouldEmitUnreachable =
1336 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1337 SanitizerHandler::MissingReturn,
1339 }
else if (ShouldEmitUnreachable) {
1343 if (
SanOpts.
has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1345 Builder.ClearInsertionPoint();
1354 if (!
CurFn->doesNotThrow())
1363 if (!S)
return false;
1370 if (isa<LabelStmt>(S))
1375 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1379 if (isa<SwitchStmt>(S))
1380 IgnoreCaseStmts =
true;
1395 if (!S)
return false;
1399 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1403 if (isa<BreakStmt>(S))
1415 if (!S)
return false;
1421 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1422 isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1423 isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1424 isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1427 if (isa<DeclStmt>(S))
1443 llvm::APSInt ResultInt;
1447 ResultBool = ResultInt.getBoolValue();
1455 llvm::APSInt &ResultInt,
1477 llvm::BasicBlock *TrueBlock,
1478 llvm::BasicBlock *FalseBlock,
1479 uint64_t TrueCount) {
1482 if (
const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1485 if (CondBOp->getOpcode() == BO_LAnd) {
1488 bool ConstantBool =
false;
1531 if (CondBOp->getOpcode() == BO_LOr) {
1534 bool ConstantBool =
false;
1560 uint64_t RHSCount = TrueCount - LHSCount;
1582 if (
const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1584 if (CondUOp->getOpcode() == UO_LNot) {
1607 uint64_t LHSScaledTrueCount = 0;
1611 LHSScaledTrueCount = TrueCount * LHSRatio;
1620 LHSScaledTrueCount);
1627 TrueCount - LHSScaledTrueCount);
1633 if (
const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1646 llvm::MDNode *Unpredictable =
nullptr;
1647 auto *Call = dyn_cast<
CallExpr>(Cond);
1649 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1650 if (FD && FD->
getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1652 Unpredictable = MDHelper.createUnpredictable();
1659 llvm::MDNode *Weights =
1660 createProfileWeights(TrueCount, CurrentCount - TrueCount);
1668 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1696 Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars,
"vla.end");
1698 llvm::BasicBlock *originBB = CGF.
Builder.GetInsertBlock();
1706 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2,
"vla.cur");
1707 cur->addIncoming(begin.getPointer(), originBB);
1718 Builder.CreateInBoundsGEP(CGF.
Int8Ty, cur, baseSizeInChars,
"vla.next");
1721 llvm::Value *done = Builder.CreateICmpEQ(next, end,
"vla-init.isdone");
1722 Builder.CreateCondBr(done, contBB, loopBB);
1723 cur->addIncoming(next, loopBB);
1733 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1752 dyn_cast_or_null<VariableArrayType>(
1756 std::tie(numElts, eltType) =
getVLASize(vlaType);
1760 if (!eltSize.
isOne())
1781 llvm::GlobalVariable *NullVariable =
1782 new llvm::GlobalVariable(
CGM.
getModule(), NullConstant->getType(),
1784 llvm::GlobalVariable::PrivateLinkage,
1785 NullConstant, Twine());
1787 NullVariable->setAlignment(NullAlign.getQuantity());
1806 if (!IndirectBranch)
1812 IndirectBranch->addDestination(BB);
1813 return llvm::BlockAddress::get(
CurFn, BB);
1818 if (IndirectBranch)
return IndirectBranch->getParent();
1824 "indirect.goto.dest");
1827 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1828 return IndirectBranch->getParent();
1841 if (isa<VariableArrayType>(arrayType)) {
1842 numVLAElements =
getVLASize(cast<VariableArrayType>(arrayType)).first;
1852 baseType = elementType;
1853 return numVLAElements;
1855 }
while (isa<VariableArrayType>(arrayType));
1867 llvm::ConstantInt *zero =
Builder.getInt32(0);
1868 gepIndices.push_back(zero);
1870 uint64_t countFromCLAs = 1;
1873 llvm::ArrayType *llvmArrayType =
1875 while (llvmArrayType) {
1876 assert(isa<ConstantArrayType>(arrayType));
1877 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1878 == llvmArrayType->getNumElements());
1880 gepIndices.push_back(zero);
1881 countFromCLAs *= llvmArrayType->getNumElements();
1885 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1887 assert((!llvmArrayType || arrayType) &&
1888 "LLVM and Clang types are out-of-synch");
1897 cast<ConstantArrayType>(
arrayType)->getSize().getZExtValue();
1907 gepIndices,
"array.begin"),
1914 = llvm::ConstantInt::get(
SizeTy, countFromCLAs);
1918 numElements =
Builder.CreateNUWMul(numVLAElements, numElements);
1923 std::pair<llvm::Value*, QualType>
1926 assert(vla &&
"type was not a variable array type!");
1930 std::pair<llvm::Value*, QualType>
1939 assert(vlaSize &&
"no size for VLA!");
1940 assert(vlaSize->getType() ==
SizeTy);
1943 numElements = vlaSize;
1947 numElements =
Builder.CreateNUWMul(numElements, vlaSize);
1949 }
while ((type =
getContext().getAsVariableArrayType(elementType)));
1951 return std::pair<llvm::Value*,QualType>(numElements, elementType);
1956 "Must pass variably modified type to EmitVLASizes!");
1966 switch (ty->getTypeClass()) {
1968 #define TYPE(Class, Base) 1969 #define ABSTRACT_TYPE(Class, Base) 1970 #define NON_CANONICAL_TYPE(Class, Base) 1971 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1972 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 1973 #include "clang/AST/TypeNodes.def" 1974 llvm_unreachable(
"unexpected dependent type!");
1980 case Type::ExtVector:
1983 case Type::Elaborated:
1984 case Type::TemplateSpecialization:
1985 case Type::ObjCTypeParam:
1986 case Type::ObjCObject:
1987 case Type::ObjCInterface:
1988 case Type::ObjCObjectPointer:
1989 llvm_unreachable(
"type class is never variably-modified!");
1991 case Type::Adjusted:
1992 type = cast<AdjustedType>(ty)->getAdjustedType();
1996 type = cast<DecayedType>(ty)->getPointeeType();
2000 type = cast<PointerType>(ty)->getPointeeType();
2003 case Type::BlockPointer:
2004 type = cast<BlockPointerType>(ty)->getPointeeType();
2007 case Type::LValueReference:
2008 case Type::RValueReference:
2009 type = cast<ReferenceType>(ty)->getPointeeType();
2012 case Type::MemberPointer:
2013 type = cast<MemberPointerType>(ty)->getPointeeType();
2016 case Type::ConstantArray:
2017 case Type::IncompleteArray:
2019 type = cast<ArrayType>(ty)->getElementType();
2022 case Type::VariableArray: {
2040 size->getType()->isSignedIntegerType()) {
2042 llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
2043 llvm::Constant *StaticArgs[] = {
2048 SanitizerKind::VLABound),
2049 SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
2061 case Type::FunctionProto:
2062 case Type::FunctionNoProto:
2063 type = cast<FunctionType>(ty)->getReturnType();
2068 case Type::UnaryTransform:
2069 case Type::Attributed:
2070 case Type::SubstTemplateTypeParm:
2071 case Type::PackExpansion:
2077 case Type::Decltype:
2079 case Type::DeducedTemplateSpecialization:
2083 case Type::TypeOfExpr:
2089 type = cast<AtomicType>(ty)->getValueType();
2093 type = cast<PipeType>(ty)->getElementType();
2100 if (
getContext().getBuiltinVaListType()->isArrayType())
2111 assert(!Init.
isUninit() &&
"Invalid DeclRefExpr initializer!");
2114 Dbg->EmitGlobalVariable(E->
getDecl(), Init);
2129 llvm::Instruction *inst =
new llvm::BitCastInst(value, value->getType(),
"",
2133 protection.Inst = inst;
2138 if (!protection.Inst)
return;
2141 protection.Inst->eraseFromParent();
2146 StringRef AnnotationStr,
2154 return Builder.CreateCall(AnnotationFn, Args);
2158 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
2169 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
2201 const llvm::Twine &Name,
2202 llvm::BasicBlock *BB,
2203 llvm::BasicBlock::iterator InsertPt)
const {
2210 llvm::Instruction *I,
const llvm::Twine &Name, llvm::BasicBlock *BB,
2211 llvm::BasicBlock::iterator InsertPt)
const {
2212 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
2219 std::string &FirstMissing) {
2221 if (ReqFeatures.empty())
2226 llvm::StringMap<bool> CallerFeatureMap;
2232 ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
2234 Feature.split(OrFeatures,
"|");
2235 return std::any_of(OrFeatures.begin(), OrFeatures.end(),
2236 [&](StringRef Feature) {
2237 if (!CallerFeatureMap.lookup(Feature)) {
2238 FirstMissing = Feature.str();
2264 std::string MissingFeature;
2267 const char *FeatureList =
2270 if (!FeatureList || StringRef(FeatureList) ==
"")
2272 StringRef(FeatureList).split(ReqFeatures,
",");
2278 }
else if (TargetDecl->
hasAttr<TargetAttr>()) {
2281 llvm::StringMap<bool> CalleeFeatureMap;
2283 for (
const auto &F : CalleeFeatureMap) {
2286 ReqFeatures.push_back(F.getKey());
2298 llvm::IRBuilder<> IRB(
Builder.GetInsertBlock(),
Builder.GetInsertPoint());
2299 IRB.SetCurrentDebugLocation(
Builder.getCurrentDebugLocation());
2305 return DI->SourceLocToDebugLoc(Location);
2307 return llvm::DebugLoc();
llvm::PointerType * Int8PtrPtrTy
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Defines the clang::ASTContext interface.
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)
Other implicit parameter.
PointerType - C99 6.7.5.1 - Pointer Declarators.
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.
const CodeGenOptions & getCodeGenOpts() const
bool isReturnsRetained() const
In ARC, whether this function retains its return value.
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler...
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
llvm::Constant * EncodeAddrForUseInPrologue(llvm::Function *F, llvm::Constant *Addr)
Encode an address into a form suitable for use in a function prologue.
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
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.
SanitizerSet Sanitize
Set of enabled sanitizers.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program...
static bool endsWithReturn(const Decl *F)
Determine whether the function F ends with a return stmt.
Checking the 'this' pointer for a constructor call.
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
Decl - This represents one declaration (or definition), e.g.
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 EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD)
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...
static void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn)
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.
bool usesSEHTry() const
Indicates the function uses __try.
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
Represents an array type, per C99 6.7.5.2 - Array Declarators.
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
bool isZero() const
isZero - Test whether the quantity equals zero.
static bool hasRequiredFeatures(const SmallVectorImpl< StringRef > &ReqFeatures, CodeGenModule &CGM, const FunctionDecl *FD, std::string &FirstMissing)
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, llvm::BasicBlock::iterator InsertPt) const
CGBuilder insert helper.
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...
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.
QualType getElementType() const
bool empty() const
Determines whether the exception-scopes stack is empty.
This file provides some common utility functions for processing Lambda related AST Constructs...
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...
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...
QualType getReturnType() const
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
const T * getAs() const
Member-template getAs<specific type>'.
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.
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
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.
DiagnosticsEngine & getDiags() const
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 ShouldXRayInstrumentFunction() const
ShouldXRayInstrument - Return true if the current function should be instrumented with XRay nop sleds...
llvm::Value * getPointer() const
virtual llvm::Constant * getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const
Return a constant used by UBSan as a signature to identify functions possessing type information...
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.
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...
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
JumpDest getJumpDestForLabel(const LabelDecl *S)
getBasicBlockForLabel - Return the LLVM basicblock that the specified label maps to.
llvm::DenseMap< const VarDecl *, FieldDecl * > LambdaCaptureFields
const TargetInfo & getTarget() const
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...
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
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 EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, SourceLocation EndLoc)
EmitFunctionEpilog - Emit the target specific LLVM code to return the given temporary.
Address getAddress() const
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
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...
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
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.
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.
field_range fields() 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
SanitizerMask Mask
Bitmask of enabled sanitizers.
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...
ArrayRef< ParmVarDecl * > parameters() const
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.
QualType getThisType(ASTContext &C) const
Returns the type of the this pointer.
static bool hasScalarEvaluationKind(QualType T)
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
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.
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
bool AlwaysEmitXRayCustomEvents() const
AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit XRay custom event handling c...
bool isOne() const
isOne - Test whether the quantity equals one.
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type...
CharUnits getAlignment() const
Return the alignment of this pointer.
virtual bool hasMostDerivedReturn(GlobalDecl GD) const
const clang::PrintingPolicy & getPrintingPolicy() const
unsigned getInAllocaFieldIndex() const
A builtin binary operation expression such as "x + y" or "x <= y".
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
The l-value was considered opaque, so the alignment was determined from a type, but that type was an ...
CXXCtorType getCtorType() const
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
bool containsOnlyLifetimeMarkers(stable_iterator Old) const
bool isLambda() const
Determine whether this class describes a lambda function object.
Values of this type can never be null.
Expr * getSizeExpr() const
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
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.
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
CharUnits getPointerAlign() const
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
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.
virtual void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args)=0
Emits a kernel launch stub.
static void removeImageAccessQualifier(std::string &TyName)
void begin(CodeGenFunction &CGF)
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.
void InsertHelper(llvm::Instruction *I) const
Function called by the CodeGenFunction when an instruction is created.
ConditionalOperator - The ?: ternary operator.
CanQualType getReturnType() const
static CharUnits One()
One - Construct a CharUnits quantity of one.
CompoundStmt - This represents a group of statements like { stmt stmt }.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
ASTContext & getContext() const
const TargetCodeGenInfo & getTargetCodeGenInfo()
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
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)
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
llvm::Value * DecodeAddrUsedInPrologue(llvm::Value *F, llvm::Value *EncodedAddr)
Decode an address used in a function prologue, encoded by EncodeAddrForUseInPrologue.
Address CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
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...
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *FD)
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
llvm::BasicBlock * EHResumeBlock
EHResumeBlock - Unified block containing a call to llvm.eh.resume.
Expr - This represents one expression.
Emit only debug info necessary for generating line number tables (-gline-tables-only).
bool isDefaulted() const
Whether this function is defaulted per C++0x.
const FunctionProtoType * T
llvm::BasicBlock * getBlock() const
bool isObjCRetainableType() 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...
llvm::AllocaInst * NormalCleanupDest
i32s containing the indexes of the cleanup destinations.
const char * getRequiredFeatures(unsigned ID) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
llvm::LLVMContext & getLLVMContext()
llvm::BasicBlock * GetIndirectGotoBlock()
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.
llvm::IntegerType * Int32Ty
static unsigned ArgInfoAddressSpace(LangAS AS)
void EmitConstructorBody(FunctionArgList &Args)
EmitConstructorBody - Emits the body of the current constructor.
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T)
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
SourceLocation getEnd() const
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.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
const LangOptions & getLangOpts() const
ASTContext & getContext() const
virtual void startNewFunction()
CallingConv
CallingConv - Specifies the calling convention that a function uses.
GlobalDecl - represents a global declaration.
SanitizerScope(CodeGenFunction *CGF)
bool isConstQualified() const
Determine whether this type is const-qualified.
VarBypassDetector Bypasses
The l-value was considered opaque, so the alignment was determined from a type.
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.
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="")
QualType getCanonicalType() const
Encodes a location in the source.
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go...
bool isSRetAfterThis() const
LangAS getAddressSpace() const
Return the address space of this type.
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
bool inheritingCtorHasParams(const InheritedConstructor &Inherited, CXXCtorType Type)
Determine if a C++ inheriting constructor should have parameters matching those of its inherited cons...
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
QualType getElementType() const
const Decl * getDecl() 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 ...
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, llvm::BasicBlock::iterator InsertPt) const
This forwards to CodeGenFunction::InsertHelper.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
Represents a static or instance method of a struct/union/class.
void EmitStmt(const Stmt *S, ArrayRef< const Attr *> Attrs=None)
EmitStmt - Emit the code for the statement.
const ParmVarDecl * getParamDecl(unsigned i) 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.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
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.
TypeClass getTypeClass() const
MangleContext & getMangleContext()
Gets the mangle context.
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.
InAlloca - Pass the argument directly using the LLVM inalloca attribute.
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
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.
FunctionArgList - Type for representing both the decl and type of parameters to a function...
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
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.
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 ...
Dataflow Directional Tag Classes.
Address EmitFieldAnnotations(const FieldDecl *D, Address V)
Emit field annotations for the given field & value.
static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx)
void Init(const Stmt *Body)
Clear the object and pre-process for the given statement, usually function body statement.
virtual ~CGCapturedStmtInfo()
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::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
llvm::IntegerType * IntPtrTy
FunctionDecl * getTemplateInstantiationPattern() const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks, lambdas, etc.
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.
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type *> Tys=None)
llvm::SmallVector< char, 256 > LifetimeExtendedCleanupStack
llvm::Module & getModule() const
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn, CodeGenModule &CGM, llvm::LLVMContext &Context, CGBuilderTy &Builder, ASTContext &ASTCtx)
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.
CodeGenTypes & getTypes() const
CharUnits getIndirectAlign() const
llvm::Type * getElementType() const
Return the type of the values stored in this address.
llvm::PointerType * Int8PtrTy
SourceLocation getLocStart() const LLVM_READONLY
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...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl)
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
FieldDecl * LambdaThisCaptureField
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
ABIArgInfo & getReturnInfo()
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...
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body)
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
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.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
void unprotectFromPeepholes(PeepholeProtection protection)
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet...
bool hasUnaligned() const
Represents a C++ struct/union/class.
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.
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
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...
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
static llvm::Constant * getPrologueSignature(CodeGenModule &CGM, const FunctionDecl *FD)
Return the UBSan prologue signature for FD if one is available.
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 ...
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
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]).
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
CGCXXABI & getCXXABI() const
const VariableArrayType * getAsVariableArrayType(QualType T) const
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.
bool isPointerType() 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.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
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())
A trivial tuple used to represent a source range.
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()
const LangOptions & getLangOpts() const
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 LValue MakeAddr(Address address, QualType type, ASTContext &Context, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
static bool containsBreak(const Stmt *S)
containsBreak - Return true if the statement contains a break out of it.
SourceLocation getBegin() const
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.
SourceLocation getLocation() const
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.
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.