35 #include "llvm/IR/DataLayout.h" 36 #include "llvm/IR/Dominators.h" 37 #include "llvm/IR/FPEnv.h" 38 #include "llvm/IR/IntrinsicInst.h" 39 #include "llvm/IR/Intrinsics.h" 40 #include "llvm/IR/MDBuilder.h" 41 #include "llvm/IR/Operator.h" 42 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 43 using namespace clang;
44 using namespace CodeGen;
50 if (CGOpts.DisableLifetimeMarkers)
54 if (CGOpts.SanitizeAddressUseAfterScope ||
60 return CGOpts.OptimizationLevel != 0;
63 CodeGenFunction::CodeGenFunction(
CodeGenModule &cgm,
bool suppressNewContext)
65 Builder(cgm, cgm.getModule().getContext(),
llvm::ConstantFolder(),
67 SanOpts(CGM.getLangOpts().Sanitize), DebugInfo(CGM.getModuleDebugInfo()),
69 CGM.getCodeGenOpts(), CGM.getLangOpts())) {
70 if (!suppressNewContext)
73 llvm::FastMathFlags FMF;
84 FMF.setNoSignedZeros();
87 FMF.setAllowReciprocal();
90 FMF.setAllowReassoc();
121 llvm_unreachable(
"Unsupported FP RoundingMode");
134 llvm_unreachable(
"Unsupported FP Exception Behavior");
143 if (fpExceptionBehavior == llvm::fp::ebIgnore &&
144 fpRoundingMode == llvm::fp::rmToNearest)
148 Builder.setIsFPConstrained(
true);
149 Builder.setDefaultConstrainedRounding(fpRoundingMode);
150 Builder.setDefaultConstrainedExcept(fpExceptionBehavior);
164 bool forPointeeType) {
172 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
200 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
241 #define TYPE(name, parent) 242 #define ABSTRACT_TYPE(name, parent) 243 #define NON_CANONICAL_TYPE(name, parent) case Type::name: 244 #define DEPENDENT_TYPE(name, parent) case Type::name: 245 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 246 #include "clang/AST/TypeNodes.inc" 247 llvm_unreachable(
"non-canonical or dependent type in IR-generation");
250 case Type::DeducedTemplateSpecialization:
251 llvm_unreachable(
"undeduced type in IR-generation");
256 case Type::BlockPointer:
257 case Type::LValueReference:
258 case Type::RValueReference:
259 case Type::MemberPointer:
261 case Type::ExtVector:
262 case Type::FunctionProto:
263 case Type::FunctionNoProto:
265 case Type::ObjCObjectPointer:
274 case Type::ConstantArray:
275 case Type::IncompleteArray:
276 case Type::VariableArray:
278 case Type::ObjCObject:
279 case Type::ObjCInterface:
284 type = cast<AtomicType>(
type)->getValueType();
287 llvm_unreachable(
"unknown type kind!");
294 llvm::BasicBlock *CurBB =
Builder.GetInsertBlock();
297 assert(!CurBB->getTerminator() &&
"Unexpected terminated block.");
307 return llvm::DebugLoc();
314 llvm::BranchInst *BI =
316 if (BI && BI->isUnconditional() &&
320 llvm::DebugLoc Loc = BI->getDebugLoc();
321 Builder.SetInsertPoint(BI->getParent());
322 BI->eraseFromParent();
334 return llvm::DebugLoc();
339 if (!BB->use_empty())
340 return CGF.
CurFn->getBasicBlockList().push_back(BB);
345 assert(BreakContinueStack.empty() &&
346 "mismatched push/pop in break/continue stack!");
348 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
349 && NumSimpleReturnExprs == NumReturnExprs
364 if (OnlySimpleReturnStmts)
365 DI->EmitLocation(
Builder, LastStopPoint);
367 DI->EmitLocation(
Builder, EndLoc);
375 bool HasOnlyLifetimeMarkers =
377 bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
383 if (OnlySimpleReturnStmts)
384 DI->EmitLocation(
Builder, EndLoc);
399 CurFn->addFnAttr(
"instrument-function-exit",
"__cyg_profile_func_exit");
401 CurFn->addFnAttr(
"instrument-function-exit-inlined",
402 "__cyg_profile_func_exit");
416 "did not remove all scopes from cleanup stack!");
420 if (IndirectBranch) {
427 if (!EscapedLocals.empty()) {
431 EscapeArgs.resize(EscapedLocals.size());
432 for (
auto &Pair : EscapedLocals)
433 EscapeArgs[Pair.second] = Pair.first;
434 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
442 Ptr->eraseFromParent();
446 if (IndirectBranch) {
447 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
448 if (PN->getNumIncomingValues() == 0) {
449 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
450 PN->eraseFromParent();
459 for (
const auto &FuncletAndParent : TerminateFunclets)
466 I = DeferredReplacements.begin(),
467 E = DeferredReplacements.end();
469 I->first->replaceAllUsesWith(I->second);
470 I->first->eraseFromParent();
480 llvm::DominatorTree DT(*
CurFn);
481 llvm::PromoteMemToReg(
487 for (llvm::Argument &A :
CurFn->args())
488 if (
auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
489 LargestVectorWidth =
std::max((uint64_t)LargestVectorWidth,
490 VT->getPrimitiveSizeInBits().getFixedSize());
493 if (
auto *VT = dyn_cast<llvm::VectorType>(
CurFn->getReturnType()))
494 LargestVectorWidth =
std::max((uint64_t)LargestVectorWidth,
495 VT->getPrimitiveSizeInBits().getFixedSize());
504 CurFn->addFnAttr(
"min-legal-vector-width", llvm::utostr(LargestVectorWidth));
513 if (RetAlloca && RetAlloca->use_empty()) {
514 RetAlloca->eraseFromParent();
556 llvm::Constant *Addr) {
564 auto *GV =
new llvm::GlobalVariable(
CGM.
getModule(), Addr->getType(),
566 llvm::GlobalValue::PrivateLinkage, Addr);
569 auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV,
IntPtrTy);
570 auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F,
IntPtrTy);
571 auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
574 : llvm::ConstantExpr::getTrunc(PCRelAsInt,
Int32Ty);
582 auto *FuncAsInt =
Builder.CreatePtrToInt(F,
IntPtrTy,
"func_addr.int");
583 auto *GOTAsInt =
Builder.CreateAdd(PCRelAsInt, FuncAsInt,
"global_addr.int");
591 void CodeGenFunction::EmitOpenCLKernelMetadata(
const FunctionDecl *FD,
594 if (!FD->
hasAttr<OpenCLKernelAttr>())
601 if (
const VecTypeHintAttr *A = FD->
getAttr<VecTypeHintAttr>()) {
602 QualType HintQTy = A->getTypeHint();
604 bool IsSignedInteger =
607 llvm::Metadata *AttrMDArgs[] = {
608 llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
610 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
611 llvm::IntegerType::get(Context, 32),
612 llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
613 Fn->setMetadata(
"vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
616 if (
const WorkGroupSizeHintAttr *A = FD->
getAttr<WorkGroupSizeHintAttr>()) {
617 llvm::Metadata *AttrMDArgs[] = {
618 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getXDim())),
619 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getYDim())),
620 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getZDim()))};
621 Fn->setMetadata(
"work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
624 if (
const ReqdWorkGroupSizeAttr *A = FD->
getAttr<ReqdWorkGroupSizeAttr>()) {
625 llvm::Metadata *AttrMDArgs[] = {
626 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getXDim())),
627 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getYDim())),
628 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getZDim()))};
629 Fn->setMetadata(
"reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
632 if (
const OpenCLIntelReqdSubGroupSizeAttr *A =
633 FD->
getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
634 llvm::Metadata *AttrMDArgs[] = {
635 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getSubGroupSize()))};
636 Fn->setMetadata(
"intel_reqd_sub_group_size",
637 llvm::MDNode::get(Context, AttrMDArgs));
643 const Stmt *Body =
nullptr;
644 if (
auto *FD = dyn_cast_or_null<FunctionDecl>(F))
646 else if (
auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
647 Body = OMD->getBody();
649 if (
auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
650 auto LastStmt = CS->body_rbegin();
651 if (LastStmt != CS->body_rend())
652 return isa<ReturnStmt>(*LastStmt);
659 Fn->addFnAttr(
"sanitize_thread_no_checking_at_run_time");
660 Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
665 bool CodeGenFunction::requiresReturnValueCheck()
const {
666 return requiresReturnValueNullabilityCheck() ||
672 auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
673 if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
674 !MD->getDeclName().getAsIdentifierInfo()->isStr(
"allocate") ||
675 (MD->getNumParams() != 1 && MD->getNumParams() != 2))
678 if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.
getSizeType())
681 if (MD->getNumParams() == 2) {
682 auto *PT = MD->parameters()[1]->getType()->getAs<
PointerType>();
683 if (!PT || !PT->isVoidPointerType() ||
684 !PT->getPointeeType().isConstQualified())
694 if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
707 "Do not use a CodeGenFunction object for more than one function");
711 DidCallStackSave =
false;
713 if (
const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
720 assert(
CurFn->isDeclaration() &&
"Function already has body?");
725 #define SANITIZER(NAME, ID) \ 726 if (SanOpts.empty()) \ 728 if (SanOpts.has(SanitizerKind::ID)) \ 729 if (CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc)) \ 730 SanOpts.set(SanitizerKind::ID, false); 732 #include "clang/Basic/Sanitizers.def" 741 if (mask & SanitizerKind::Address)
742 SanOpts.
set(SanitizerKind::KernelAddress,
false);
743 if (mask & SanitizerKind::KernelAddress)
745 if (mask & SanitizerKind::HWAddress)
746 SanOpts.
set(SanitizerKind::KernelHWAddress,
false);
747 if (mask & SanitizerKind::KernelHWAddress)
753 if (
SanOpts.
hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
754 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
755 if (
SanOpts.
hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
756 Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
758 Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
760 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
761 if (
SanOpts.
hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
762 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
764 Fn->addFnAttr(llvm::Attribute::SafeStack);
765 if (
SanOpts.
has(SanitizerKind::ShadowCallStack))
766 Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
769 if (
SanOpts.
hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
770 Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
775 if (
const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
776 IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
779 (OMD->getSelector().isUnarySelector() && II->
isStr(
".cxx_destruct"))) {
788 if (D &&
SanOpts.
has(SanitizerKind::CFIUnrelatedCast)) {
797 if (
const auto *FD = dyn_cast<FunctionDecl>(D))
804 if (
const auto *XRayAttr = D->
getAttr<XRayInstrumentAttr>()) {
808 Fn->addFnAttr(
"function-instrument",
"xray-always");
809 if (XRayAttr->neverXRayInstrument())
810 Fn->addFnAttr(
"function-instrument",
"xray-never");
811 if (
const auto *LogArgs = D->
getAttr<XRayLogArgsAttr>())
813 Fn->addFnAttr(
"xray-log-args",
814 llvm::utostr(LogArgs->getArgumentCount()));
819 "xray-instruction-threshold",
824 if (
const auto *
Attr = D->
getAttr<PatchableFunctionEntryAttr>()) {
825 Count =
Attr->getCount();
826 Offset =
Attr->getOffset();
831 if (Count && Offset <= Count) {
832 Fn->addFnAttr(
"patchable-function-entry", std::to_string(Count - Offset));
834 Fn->addFnAttr(
"patchable-function-prefix", std::to_string(Offset));
839 Fn->addFnAttr(
"no-jump-tables",
844 Fn->addFnAttr(
"no-inline-line-tables");
848 Fn->addFnAttr(
"profile-sample-accurate");
850 if (D && D->
hasAttr<CFICanonicalJumpTableAttr>())
851 Fn->addFnAttr(
"cfi-canonical-jump-table");
855 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
856 EmitOpenCLKernelMetadata(FD, Fn);
862 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
869 llvm::Constant *FTRTTIConst =
871 llvm::Constant *FTRTTIConstEncoded =
873 llvm::Constant *PrologueStructElems[] = {PrologueSig,
875 llvm::Constant *PrologueStructConst =
876 llvm::ConstantStruct::getAnon(PrologueStructElems,
true);
877 Fn->setPrologueData(PrologueStructConst);
884 if (
SanOpts.
has(SanitizerKind::NullabilityReturn)) {
887 if (!(
SanOpts.
has(SanitizerKind::ReturnsNonnullAttribute) &&
889 RetValNullabilityPrecondition =
898 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
900 Fn->addFnAttr(llvm::Attribute::NoRecurse);
902 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
904 Fn->addFnAttr(llvm::Attribute::StrictFP);
908 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
911 Fn->addFnAttr(
"stackrealign");
923 Builder.SetInsertPoint(EntryBB);
927 if (requiresReturnValueCheck()) {
938 if (
auto *FD = dyn_cast_or_null<FunctionDecl>(D))
940 CC = SrcFnTy->getCallConv();
943 ArgTypes.push_back(VD->getType());
952 CurFn->addFnAttr(
"instrument-function-entry",
"__cyg_profile_func_enter");
954 CurFn->addFnAttr(
"instrument-function-entry-inlined",
955 "__cyg_profile_func_enter");
957 CurFn->addFnAttr(
"instrument-function-entry-inlined",
958 "__cyg_profile_func_enter_bare");
970 Fn->addFnAttr(
"fentry-call",
"true");
972 Fn->addFnAttr(
"instrument-function-entry-inlined",
978 <<
"-mnop-mcount" <<
"-mfentry";
979 Fn->addFnAttr(
"mnop-mcount");
985 <<
"-mrecord-mcount" <<
"-mfentry";
986 Fn->addFnAttr(
"mrecord-mcount");
993 llvm::Triple::systemz)
996 Fn->addFnAttr(
"packed-stack");
1009 auto AI =
CurFn->arg_begin();
1024 llvm::Function::arg_iterator EI =
CurFn->arg_end();
1052 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
1079 if (FD->hasCapturedVLAType()) {
1082 auto VAT = FD->getCapturedVLAType();
1083 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1090 CXXThisValue = CXXABIThisValue;
1094 if (CXXABIThisValue) {
1096 SkippedChecks.
set(SanitizerKind::ObjectSize,
true);
1108 Loc, CXXABIThisValue, ThisTy,
1116 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1124 if (
const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1125 Ty = PVD->getOriginalType();
1134 DI->EmitLocation(
Builder, StartLoc);
1140 LargestVectorWidth = VecWidth->getVectorWidth();
1145 if (
const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1157 llvm::BasicBlock *SkipCountBB =
nullptr;
1179 if (F->isInterposable())
return;
1181 for (llvm::BasicBlock &BB : *F)
1182 for (llvm::Instruction &I : BB)
1186 F->setDoesNotThrow();
1206 bool PassedParams =
true;
1208 if (
auto Inherited = CD->getInheritedConstructor())
1214 Args.push_back(Param);
1215 if (!Param->hasAttr<PassObjectSizeAttr>())
1219 getContext(), Param->getDeclContext(), Param->getLocation(),
1221 SizeArguments[Param] = Implicit;
1222 Args.push_back(Implicit);
1226 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1239 if (
const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1240 return !ClassDecl->hasTrivialDestructor();
1254 if (FD->
hasAttr<NoDebugAttr>())
1255 DebugInfo =
nullptr;
1261 BodyRange = Body->getSourceRange();
1264 CurEHLocation = BodyRange.
getEnd();
1276 if (SpecDecl->hasBody(SpecDecl))
1277 Loc = SpecDecl->getLocation();
1283 if (Body && ShouldEmitLifetimeMarkers)
1291 if (isa<CXXDestructorDecl>(FD))
1293 else if (isa<CXXConstructorDecl>(FD))
1297 FD->
hasAttr<CUDAGlobalAttr>())
1299 else if (isa<CXXMethodDecl>(FD) &&
1300 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1304 }
else if (FD->
isDefaulted() && isa<CXXMethodDecl>(FD) &&
1305 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1306 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1313 llvm_unreachable(
"no definition for emitted function");
1323 bool ShouldEmitUnreachable =
1329 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1330 SanitizerHandler::MissingReturn,
1332 }
else if (ShouldEmitUnreachable) {
1336 if (
SanOpts.
has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1338 Builder.ClearInsertionPoint();
1347 if (!
CurFn->doesNotThrow())
1356 if (!S)
return false;
1363 if (isa<LabelStmt>(S))
1368 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1372 if (isa<SwitchStmt>(S))
1373 IgnoreCaseStmts =
true;
1388 if (!S)
return false;
1392 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1396 if (isa<BreakStmt>(S))
1408 if (!S)
return false;
1414 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1415 isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1416 isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1417 isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1420 if (isa<DeclStmt>(S))
1440 ResultBool = ResultInt.getBoolValue();
1471 llvm::BasicBlock *TrueBlock,
1472 llvm::BasicBlock *FalseBlock,
1473 uint64_t TrueCount) {
1476 if (
const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1479 if (CondBOp->getOpcode() == BO_LAnd) {
1482 bool ConstantBool =
false;
1525 if (CondBOp->getOpcode() == BO_LOr) {
1528 bool ConstantBool =
false;
1554 uint64_t RHSCount = TrueCount - LHSCount;
1576 if (
const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1578 if (CondUOp->getOpcode() == UO_LNot) {
1601 uint64_t LHSScaledTrueCount = 0;
1605 LHSScaledTrueCount = TrueCount * LHSRatio;
1614 LHSScaledTrueCount);
1621 TrueCount - LHSScaledTrueCount);
1627 if (
const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1640 llvm::MDNode *Unpredictable =
nullptr;
1643 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1644 if (FD && FD->
getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1646 Unpredictable = MDHelper.createUnpredictable();
1653 llvm::MDNode *Weights =
1654 createProfileWeights(TrueCount, CurrentCount - TrueCount);
1662 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1690 Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars,
"vla.end");
1692 llvm::BasicBlock *originBB = CGF.
Builder.GetInsertBlock();
1700 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2,
"vla.cur");
1701 cur->addIncoming(begin.getPointer(), originBB);
1712 Builder.CreateInBoundsGEP(CGF.
Int8Ty, cur, baseSizeInChars,
"vla.next");
1715 llvm::Value *done = Builder.CreateICmpEQ(next, end,
"vla-init.isdone");
1716 Builder.CreateCondBr(done, contBB, loopBB);
1717 cur->addIncoming(next, loopBB);
1727 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1746 dyn_cast_or_null<VariableArrayType>(
1749 SizeVal = VlaSize.NumElts;
1751 if (!eltSize.
isOne())
1772 llvm::GlobalVariable *NullVariable =
1773 new llvm::GlobalVariable(
CGM.
getModule(), NullConstant->getType(),
1775 llvm::GlobalVariable::PrivateLinkage,
1776 NullConstant, Twine());
1778 NullVariable->setAlignment(NullAlign.getAsAlign());
1797 if (!IndirectBranch)
1803 IndirectBranch->addDestination(BB);
1804 return llvm::BlockAddress::get(
CurFn, BB);
1809 if (IndirectBranch)
return IndirectBranch->getParent();
1815 "indirect.goto.dest");
1818 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1819 return IndirectBranch->getParent();
1832 if (isa<VariableArrayType>(arrayType)) {
1843 baseType = elementType;
1844 return numVLAElements;
1846 }
while (isa<VariableArrayType>(arrayType));
1858 llvm::ConstantInt *zero =
Builder.getInt32(0);
1859 gepIndices.push_back(zero);
1861 uint64_t countFromCLAs = 1;
1864 llvm::ArrayType *llvmArrayType =
1866 while (llvmArrayType) {
1867 assert(isa<ConstantArrayType>(arrayType));
1868 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1869 == llvmArrayType->getNumElements());
1871 gepIndices.push_back(zero);
1872 countFromCLAs *= llvmArrayType->getNumElements();
1876 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1878 assert((!llvmArrayType || arrayType) &&
1879 "LLVM and Clang types are out-of-synch");
1888 cast<ConstantArrayType>(
arrayType)->getSize().getZExtValue();
1898 gepIndices,
"array.begin"),
1905 = llvm::ConstantInt::get(
SizeTy, countFromCLAs);
1909 numElements =
Builder.CreateNUWMul(numVLAElements, numElements);
1916 assert(vla &&
"type was not a variable array type!");
1929 assert(vlaSize &&
"no size for VLA!");
1930 assert(vlaSize->getType() ==
SizeTy);
1933 numElements = vlaSize;
1937 numElements =
Builder.CreateNUWMul(numElements, vlaSize);
1939 }
while ((type =
getContext().getAsVariableArrayType(elementType)));
1941 return { numElements, elementType };
1947 assert(vla &&
"type was not a variable array type!");
1954 assert(VlaSize &&
"no size for VLA!");
1955 assert(VlaSize->getType() ==
SizeTy);
1961 "Must pass variably modified type to EmitVLASizes!");
1971 switch (ty->getTypeClass()) {
1973 #define TYPE(Class, Base) 1974 #define ABSTRACT_TYPE(Class, Base) 1975 #define NON_CANONICAL_TYPE(Class, Base) 1976 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1977 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 1978 #include "clang/AST/TypeNodes.inc" 1979 llvm_unreachable(
"unexpected dependent type!");
1985 case Type::ExtVector:
1988 case Type::Elaborated:
1989 case Type::TemplateSpecialization:
1990 case Type::ObjCTypeParam:
1991 case Type::ObjCObject:
1992 case Type::ObjCInterface:
1993 case Type::ObjCObjectPointer:
1994 llvm_unreachable(
"type class is never variably-modified!");
1996 case Type::Adjusted:
1997 type = cast<AdjustedType>(ty)->getAdjustedType();
2001 type = cast<DecayedType>(ty)->getPointeeType();
2005 type = cast<PointerType>(ty)->getPointeeType();
2008 case Type::BlockPointer:
2009 type = cast<BlockPointerType>(ty)->getPointeeType();
2012 case Type::LValueReference:
2013 case Type::RValueReference:
2014 type = cast<ReferenceType>(ty)->getPointeeType();
2017 case Type::MemberPointer:
2018 type = cast<MemberPointerType>(ty)->getPointeeType();
2021 case Type::ConstantArray:
2022 case Type::IncompleteArray:
2024 type = cast<ArrayType>(ty)->getElementType();
2027 case Type::VariableArray: {
2045 size->getType()->isSignedIntegerType()) {
2048 llvm::Constant *StaticArgs[] = {
2052 SanitizerKind::VLABound),
2053 SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
2065 case Type::FunctionProto:
2066 case Type::FunctionNoProto:
2067 type = cast<FunctionType>(ty)->getReturnType();
2072 case Type::UnaryTransform:
2073 case Type::Attributed:
2074 case Type::SubstTemplateTypeParm:
2075 case Type::PackExpansion:
2076 case Type::MacroQualified:
2082 case Type::Decltype:
2084 case Type::DeducedTemplateSpecialization:
2088 case Type::TypeOfExpr:
2094 type = cast<AtomicType>(ty)->getValueType();
2098 type = cast<PipeType>(ty)->getElementType();
2105 if (
getContext().getBuiltinVaListType()->isArrayType())
2116 assert(Init.
hasValue() &&
"Invalid DeclRefExpr initializer!");
2119 Dbg->EmitGlobalVariable(E->
getDecl(), Init);
2134 llvm::Instruction *inst =
new llvm::BitCastInst(value, value->getType(),
"",
2138 protection.Inst = inst;
2143 if (!protection.Inst)
return;
2146 protection.Inst->eraseFromParent();
2155 llvm::Instruction *Assumption =
Builder.CreateAlignmentAssumption(
2159 OffsetValue, TheCheck, Assumption);
2168 if (
auto *CE = dyn_cast<CastExpr>(E))
2169 E = CE->getSubExprAsWritten();
2179 StringRef AnnotationStr,
2187 return Builder.CreateCall(AnnotationFn, Args);
2191 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
2202 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
2234 const llvm::Twine &Name,
2235 llvm::BasicBlock *BB,
2236 llvm::BasicBlock::iterator InsertPt)
const {
2243 llvm::Instruction *I,
const llvm::Twine &Name, llvm::BasicBlock *BB,
2244 llvm::BasicBlock::iterator InsertPt)
const {
2245 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
2252 std::string &FirstMissing) {
2254 if (ReqFeatures.empty())
2259 llvm::StringMap<bool> CallerFeatureMap;
2265 ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
2267 Feature.split(OrFeatures,
'|');
2268 return llvm::any_of(OrFeatures, [&](StringRef Feature) {
2269 if (!CallerFeatureMap.lookup(Feature)) {
2270 FirstMissing = Feature.str();
2303 std::string MissingFeature;
2306 const char *FeatureList =
2309 if (!FeatureList || StringRef(FeatureList) ==
"")
2311 StringRef(FeatureList).split(ReqFeatures,
',');
2318 TargetDecl->
hasAttr<TargetAttr>()) {
2321 const TargetAttr *TD = TargetDecl->
getAttr<TargetAttr>();
2326 llvm::StringMap<bool> CalleeFeatureMap;
2330 for (
const auto &F : ParsedAttr.Features) {
2331 if (F[0] ==
'+' && CalleeFeatureMap.lookup(F.substr(1)))
2332 ReqFeatures.push_back(StringRef(F).substr(1));
2335 for (
const auto &F : CalleeFeatureMap) {
2338 ReqFeatures.push_back(F.getKey());
2350 llvm::IRBuilder<> IRB(
Builder.GetInsertBlock(),
Builder.GetInsertPoint());
2351 IRB.SetCurrentDebugLocation(
Builder.getCurrentDebugLocation());
2365 Condition ?
Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
2371 llvm::Function *Resolver,
2373 llvm::Function *FuncToReturn,
2374 bool SupportsIFunc) {
2375 if (SupportsIFunc) {
2376 Builder.CreateRet(FuncToReturn);
2381 llvm::for_each(Resolver->args(),
2382 [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
2384 llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2385 Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2387 if (Resolver->getReturnType()->isVoidTy())
2388 Builder.CreateRetVoid();
2390 Builder.CreateRet(Result);
2395 assert(
getContext().getTargetInfo().getTriple().isX86() &&
2396 "Only implemented for x86 targets");
2402 Builder.SetInsertPoint(CurBlock);
2406 Builder.SetInsertPoint(CurBlock);
2407 llvm::Value *Condition = FormResolverCondition(RO);
2411 assert(&RO == Options.end() - 1 &&
2412 "Default or Generic case must be last");
2418 llvm::BasicBlock *RetBlock =
createBasicBlock(
"resolver_return", Resolver);
2423 Builder.CreateCondBr(Condition, RetBlock, CurBlock);
2427 Builder.SetInsertPoint(CurBlock);
2428 llvm::CallInst *TrapCall =
EmitTrapCall(llvm::Intrinsic::trap);
2429 TrapCall->setDoesNotReturn();
2430 TrapCall->setDoesNotThrow();
2432 Builder.ClearInsertionPoint();
2445 llvm::Instruction *Assumption) {
2446 assert(Assumption && isa<llvm::CallInst>(Assumption) &&
2447 cast<llvm::CallInst>(Assumption)->getCalledValue() ==
2448 llvm::Intrinsic::getDeclaration(
2449 Builder.GetInsertBlock()->getParent()->getParent(),
2450 llvm::Intrinsic::assume) &&
2451 "Assumption should be a call to llvm.assume().");
2452 assert(&(
Builder.GetInsertBlock()->back()) == Assumption &&
2453 "Assumption should be the last instruction of the basic block, " 2454 "since the basic block is still being generated.");
2466 Assumption->removeFromParent();
2472 OffsetValue =
Builder.getInt1(0);
2480 EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
2481 SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
2492 return DI->SourceLocToDebugLoc(Location);
2494 return llvm::DebugLoc();
llvm::PointerType * Int8PtrPtrTy
const llvm::DataLayout & getDataLayout() const
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Defines the clang::ASTContext interface.
Represents 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.
no exception specification
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
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.
Specialize PointerLikeTypeTraits to allow LazyGenerationalUpdatePtr to be placed into a PointerUnion...
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...
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
static bool endsWithReturn(const Decl *F)
Determine whether the function F ends with a return stmt.
QualType getThisType() const
Return the type of the this pointer.
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...
constexpr XRayInstrMask Typed
Decl - This represents one declaration (or definition), e.g.
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 either trap or call a handler function in the UBSan runtime with the p...
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 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.
const TargetInfo & getTargetInfo() const
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...
constexpr XRayInstrMask Function
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.
FPRoundingModeKind
Possible rounding modes.
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.
Represents 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.
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...
void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn)
Annotate the function with an attribute that disables TSan checking at runtime.
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
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]).
bool supportsIFunc() const
Identify whether this target supports IFuncs.
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...
A jump destination is an abstract label, branching to which may require a jump out through normal cle...
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
Get the actual, stored name of the declaration, which may be a special name.
void EmitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue, llvm::Value *TheCheck, llvm::Instruction *Assumption)
One of these records is kept for each identifier that is lexed.
VlaSizePair getVLAElements1D(const VariableArrayType *vla)
Return the number of elements for a single dimension for the given array type.
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.
static void CreateMultiVersionResolverReturn(CodeGenModule &CGM, llvm::Function *Resolver, CGBuilderTy &Builder, llvm::Function *FuncToReturn, bool SupportsIFunc)
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.
const NamedDecl * CurSEHParent
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
Represents a member of a struct/union/class.
llvm::IntegerType * SizeTy
bool usesFPIntrin() const
Indicates the function uses Floating Point constrained intrinsics.
bool Zero(InterpState &S, CodePtr OpPC)
SanitizerMask Mask
Bitmask of enabled sanitizers.
__DEVICE__ int max(int __a, int __b)
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...
bool AlwaysEmitXRayTypedEvents() const
AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit XRay typed event handling ...
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.
Is determined by runtime environment, corresponds to "round.dynamic".
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
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.
APValue Val
Val - This is the value the expression can be folded to.
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
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.
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Address NormalCleanupDest
i32s containing the indexes of the cleanup destinations.
virtual void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args)=0
Emits a kernel launch stub.
llvm::Value * EmitCheckValue(llvm::Value *V)
Convert a value into a format suitable for passing to a runtime sanitizer handler.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point...
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.
Rounding toward +Inf, corresponds to "round.upward".
ConditionalOperator - The ?: ternary operator.
CanQualType getReturnType() const
static CharUnits One()
One - Construct a CharUnits quantity of one.
Contains information gathered from parsing the contents of TargetAttr.
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
static llvm::fp::ExceptionBehavior ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind)
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 llvm::fp::RoundingMode ToConstrainedRoundingMD(LangOptions::FPRoundingModeKind Kind)
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...
llvm::SmallVector< StringRef, 8 > Features
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.
bool isMultiVersion() const
True if this function is considered a multiversioned function.
This represents one expression.
bool isDefaulted() const
Whether this function is defaulted per C++0x.
Address getAddress(CodeGenFunction &CGF) const
llvm::BasicBlock * getBlock() const
bool isObjCRetainableType() const
FPExceptionModeKind
Possible floating point exception behavior.
static void TryMarkNoThrow(llvm::Function *F)
Tries to mark the given function nounwind based on the non-existence of any throwing calls within it...
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements, of a variable length array type, plus that largest non-variably-sized element type.
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()
void GenOpenCLArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
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
void EmitConstructorBody(FunctionArgList &Args)
EmitConstructorBody - Emits the body of the current constructor.
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, QualType Type, CharUnits Alignment=CharUnits::Zero(), SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
Emit a check that V is the address of storage of the appropriate size and alignment for an object of ...
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
bool getIndirectByVal() const
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
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI)
Get a function type and produce the equivalent function type with the specified exception specificati...
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)
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...
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names...
bool isSRetAfterThis() const
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).
Rounding to nearest, corresponds to "round.tonearest".
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
Represents the declaration of a label.
ParsedAttr - Represents a syntactic attribute.
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.
SanitizerSet SanOpts
Sanitizers enabled for this function.
constexpr XRayInstrMask Custom
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.
Rounding toward -Inf, corresponds to "round.downward".
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.
Address ReturnValuePointer
ReturnValuePointer - The temporary alloca to hold a pointer to sret.
XRayInstrSet XRayInstrumentationBundle
Set of XRay instrumentation kinds to emit.
TypeClass getTypeClass() const
MangleContext & getMangleContext()
Gets the mangle context.
void SetFPModel()
SetFPModel - Control floating point behavior via fp-model settings.
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.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
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 ...
llvm::Value * EmitAnnotationCall(llvm::Function *AnnotationFn, llvm::Value *AnnotatedVal, StringRef AnnotationStr, SourceLocation Location)
Emit an annotation call (intrinsic).
Dataflow Directional Tag Classes.
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid.
Assume that floating-point exceptions are masked.
Address EmitFieldAnnotations(const FieldDecl *D, Address V)
Emit field annotations for the given field & value.
EvalResult is a struct with detailed info about an evaluated expression.
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()
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...
StmtClass getStmtClass() const
void EmitFunctionBody(const Stmt *Body)
const CXXRecordDecl * getParent() const
Return 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.
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
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
bool has(XRayInstrMask K) const
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
llvm::Module & getModule() const
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
JumpDest ReturnBlock
ReturnBlock - Unified return block.
Rounding toward zero, corresponds to "round.towardzero".
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
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.
bool hasReducedDebugInfo() const
Check if type and variable info should be emitted.
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...
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).
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
void unprotectFromPeepholes(PeepholeProtection protection)
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.
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.
LambdaCaptureDefault getLambdaCaptureDefault() const
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
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
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.
llvm::Function * Function
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
void EmitMultiVersionResolver(llvm::Function *Resolver, ArrayRef< MultiVersionResolverOption > Options)
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.
struct clang::CodeGen::CodeGenFunction::MultiVersionResolverOption::Conds Conditions
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...
bool Null(InterpState &S, CodePtr OpPC)
Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
void EmitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
A trivial tuple used to represent a source range.
LValue - This represents an lvalue references.
llvm::BlockAddress * GetAddrOfLabel(const LabelDecl *L)
SourceLocation getBeginLoc() const LLVM_READONLY
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.
Strictly preserve the floating-point exception semantics.
SanitizerMetadata * getSanitizerMetadata()
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
const LangOptions & getLangOpts() const
Address CreatePointerBitCastOrAddrSpaceCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
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)
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
Skip past any parentheses which might surround this expression until reaching a fixed point...
Transformations do not cause new exceptions but may hide some.
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.