34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/Dominators.h" 36 #include "llvm/IR/Intrinsics.h" 37 #include "llvm/IR/MDBuilder.h" 38 #include "llvm/IR/Operator.h" 39 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 40 using namespace clang;
41 using namespace CodeGen;
47 if (CGOpts.DisableLifetimeMarkers)
56 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();
118 bool forPointeeType) {
126 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
154 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
195 #define TYPE(name, parent) 196 #define ABSTRACT_TYPE(name, parent) 197 #define NON_CANONICAL_TYPE(name, parent) case Type::name: 198 #define DEPENDENT_TYPE(name, parent) case Type::name: 199 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 200 #include "clang/AST/TypeNodes.def" 201 llvm_unreachable(
"non-canonical or dependent type in IR-generation");
204 case Type::DeducedTemplateSpecialization:
205 llvm_unreachable(
"undeduced type in IR-generation");
210 case Type::BlockPointer:
211 case Type::LValueReference:
212 case Type::RValueReference:
213 case Type::MemberPointer:
215 case Type::ExtVector:
216 case Type::FunctionProto:
217 case Type::FunctionNoProto:
219 case Type::ObjCObjectPointer:
228 case Type::ConstantArray:
229 case Type::IncompleteArray:
230 case Type::VariableArray:
232 case Type::ObjCObject:
233 case Type::ObjCInterface:
238 type = cast<AtomicType>(
type)->getValueType();
241 llvm_unreachable(
"unknown type kind!");
248 llvm::BasicBlock *CurBB =
Builder.GetInsertBlock();
251 assert(!CurBB->getTerminator() &&
"Unexpected terminated block.");
261 return llvm::DebugLoc();
268 llvm::BranchInst *BI =
270 if (BI && BI->isUnconditional() &&
274 llvm::DebugLoc Loc = BI->getDebugLoc();
275 Builder.SetInsertPoint(BI->getParent());
276 BI->eraseFromParent();
288 return llvm::DebugLoc();
293 if (!BB->use_empty())
294 return CGF.
CurFn->getBasicBlockList().push_back(BB);
299 assert(BreakContinueStack.empty() &&
300 "mismatched push/pop in break/continue stack!");
302 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
303 && NumSimpleReturnExprs == NumReturnExprs
318 if (OnlySimpleReturnStmts)
319 DI->EmitLocation(
Builder, LastStopPoint);
321 DI->EmitLocation(
Builder, EndLoc);
329 bool HasOnlyLifetimeMarkers =
331 bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
336 if (OnlySimpleReturnStmts)
337 DI->EmitLocation(
Builder, EndLoc);
347 CurFn->addFnAttr(
"instrument-function-exit",
"__cyg_profile_func_exit");
349 CurFn->addFnAttr(
"instrument-function-exit-inlined",
350 "__cyg_profile_func_exit");
364 "did not remove all scopes from cleanup stack!");
368 if (IndirectBranch) {
375 if (!EscapedLocals.empty()) {
379 EscapeArgs.resize(EscapedLocals.size());
380 for (
auto &Pair : EscapedLocals)
381 EscapeArgs[Pair.second] = Pair.first;
382 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
390 Ptr->eraseFromParent();
394 if (IndirectBranch) {
395 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
396 if (PN->getNumIncomingValues() == 0) {
397 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
398 PN->eraseFromParent();
407 for (
const auto &FuncletAndParent : TerminateFunclets)
413 for (
SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
414 I = DeferredReplacements.begin(),
415 E = DeferredReplacements.end();
417 I->first->replaceAllUsesWith(I->second);
418 I->first->eraseFromParent();
428 llvm::DominatorTree DT(*
CurFn);
429 llvm::PromoteMemToReg(
435 for (llvm::Argument &A :
CurFn->args())
436 if (
auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
437 LargestVectorWidth =
std::max(LargestVectorWidth,
438 VT->getPrimitiveSizeInBits());
441 if (
auto *VT = dyn_cast<llvm::VectorType>(
CurFn->getReturnType()))
442 LargestVectorWidth =
std::max(LargestVectorWidth,
443 VT->getPrimitiveSizeInBits());
452 CurFn->addFnAttr(
"min-legal-vector-width", llvm::utostr(LargestVectorWidth));
461 if (RetAlloca && RetAlloca->use_empty()) {
462 RetAlloca->eraseFromParent();
504 llvm::Constant *Addr) {
512 auto *GV =
new llvm::GlobalVariable(
CGM.
getModule(), Addr->getType(),
514 llvm::GlobalValue::PrivateLinkage, Addr);
517 auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV,
IntPtrTy);
518 auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F,
IntPtrTy);
519 auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
522 : llvm::ConstantExpr::getTrunc(PCRelAsInt,
Int32Ty);
530 auto *FuncAsInt =
Builder.CreatePtrToInt(F,
IntPtrTy,
"func_addr.int");
531 auto *GOTAsInt =
Builder.CreateAdd(PCRelAsInt, FuncAsInt,
"global_addr.int");
539 void CodeGenFunction::EmitOpenCLKernelMetadata(
const FunctionDecl *FD,
542 if (!FD->
hasAttr<OpenCLKernelAttr>())
549 if (
const VecTypeHintAttr *A = FD->
getAttr<VecTypeHintAttr>()) {
550 QualType HintQTy = A->getTypeHint();
552 bool IsSignedInteger =
555 llvm::Metadata *AttrMDArgs[] = {
556 llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
558 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
559 llvm::IntegerType::get(Context, 32),
560 llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
561 Fn->setMetadata(
"vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
564 if (
const WorkGroupSizeHintAttr *A = FD->
getAttr<WorkGroupSizeHintAttr>()) {
565 llvm::Metadata *AttrMDArgs[] = {
566 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getXDim())),
567 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getYDim())),
568 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getZDim()))};
569 Fn->setMetadata(
"work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
572 if (
const ReqdWorkGroupSizeAttr *A = FD->
getAttr<ReqdWorkGroupSizeAttr>()) {
573 llvm::Metadata *AttrMDArgs[] = {
574 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getXDim())),
575 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getYDim())),
576 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getZDim()))};
577 Fn->setMetadata(
"reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
580 if (
const OpenCLIntelReqdSubGroupSizeAttr *A =
581 FD->
getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
582 llvm::Metadata *AttrMDArgs[] = {
583 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getSubGroupSize()))};
584 Fn->setMetadata(
"intel_reqd_sub_group_size",
585 llvm::MDNode::get(Context, AttrMDArgs));
591 const Stmt *Body =
nullptr;
592 if (
auto *FD = dyn_cast_or_null<FunctionDecl>(F))
594 else if (
auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
595 Body = OMD->getBody();
597 if (
auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
598 auto LastStmt = CS->body_rbegin();
599 if (LastStmt != CS->body_rend())
600 return isa<ReturnStmt>(*LastStmt);
607 Fn->addFnAttr(
"sanitize_thread_no_checking_at_run_time");
608 Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
613 auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
614 if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
615 !MD->getDeclName().getAsIdentifierInfo()->isStr(
"allocate") ||
616 (MD->getNumParams() != 1 && MD->getNumParams() != 2))
619 if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.
getSizeType())
622 if (MD->getNumParams() == 2) {
623 auto *PT = MD->parameters()[1]->getType()->getAs<
PointerType>();
624 if (!PT || !PT->isVoidPointerType() ||
625 !PT->getPointeeType().isConstQualified())
635 if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
649 "Do not use a CodeGenFunction object for more than one function");
653 DidCallStackSave =
false;
655 if (
const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
662 assert(
CurFn->isDeclaration() &&
"Function already has body?");
667 #define SANITIZER(NAME, ID) \ 668 if (SanOpts.empty()) \ 670 if (SanOpts.has(SanitizerKind::ID)) \ 671 if (CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc)) \ 672 SanOpts.set(SanitizerKind::ID, false); 674 #include "clang/Basic/Sanitizers.def" 683 if (mask & SanitizerKind::Address)
684 SanOpts.
set(SanitizerKind::KernelAddress,
false);
685 if (mask & SanitizerKind::KernelAddress)
687 if (mask & SanitizerKind::HWAddress)
688 SanOpts.
set(SanitizerKind::KernelHWAddress,
false);
689 if (mask & SanitizerKind::KernelHWAddress)
695 if (
SanOpts.
hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
696 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
697 if (
SanOpts.
hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
698 Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
700 Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
702 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
703 if (
SanOpts.
hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
704 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
706 Fn->addFnAttr(llvm::Attribute::SafeStack);
707 if (
SanOpts.
has(SanitizerKind::ShadowCallStack))
708 Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
711 if (
SanOpts.
hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
712 Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
717 if (
const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
718 IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
721 (OMD->getSelector().isUnarySelector() && II->
isStr(
".cxx_destruct"))) {
730 if (D &&
SanOpts.
has(SanitizerKind::CFIUnrelatedCast)) {
737 if (
const auto *XRayAttr = D->
getAttr<XRayInstrumentAttr>()) {
741 Fn->addFnAttr(
"function-instrument",
"xray-always");
742 if (XRayAttr->neverXRayInstrument())
743 Fn->addFnAttr(
"function-instrument",
"xray-never");
744 if (
const auto *LogArgs = D->
getAttr<XRayLogArgsAttr>())
746 Fn->addFnAttr(
"xray-log-args",
747 llvm::utostr(LogArgs->getArgumentCount()));
752 "xray-instruction-threshold",
758 Fn->addFnAttr(
"no-jump-tables",
763 Fn->addFnAttr(
"profile-sample-accurate");
767 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
768 EmitOpenCLKernelMetadata(FD, Fn);
774 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
781 llvm::Constant *FTRTTIConst =
783 llvm::Constant *FTRTTIConstEncoded =
785 llvm::Constant *PrologueStructElems[] = {PrologueSig,
787 llvm::Constant *PrologueStructConst =
788 llvm::ConstantStruct::getAnon(PrologueStructElems,
true);
789 Fn->setPrologueData(PrologueStructConst);
796 if (
SanOpts.
has(SanitizerKind::NullabilityReturn)) {
799 if (!(
SanOpts.
has(SanitizerKind::ReturnsNonnullAttribute) &&
801 RetValNullabilityPrecondition =
810 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
812 Fn->addFnAttr(llvm::Attribute::NoRecurse);
816 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
819 Fn->addFnAttr(
"stackrealign");
831 Builder.SetInsertPoint(EntryBB);
835 if (requiresReturnValueCheck()) {
846 if (
auto *FD = dyn_cast_or_null<FunctionDecl>(D))
848 CC = SrcFnTy->getCallConv();
851 ArgTypes.push_back(VD->getType());
860 CurFn->addFnAttr(
"instrument-function-entry",
"__cyg_profile_func_enter");
862 CurFn->addFnAttr(
"instrument-function-entry-inlined",
863 "__cyg_profile_func_enter");
865 CurFn->addFnAttr(
"instrument-function-entry-inlined",
866 "__cyg_profile_func_enter_bare");
878 Fn->addFnAttr(
"fentry-call",
"true");
880 Fn->addFnAttr(
"instrument-function-entry-inlined",
896 auto AI =
CurFn->arg_begin();
911 llvm::Function::arg_iterator EI =
CurFn->arg_end();
939 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
966 if (FD->hasCapturedVLAType()) {
969 auto VAT = FD->getCapturedVLAType();
970 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
977 CXXThisValue = CXXABIThisValue;
981 if (CXXABIThisValue) {
983 SkippedChecks.
set(SanitizerKind::ObjectSize,
true);
991 SkippedChecks.
set(SanitizerKind::Null,
true);
995 Loc, CXXABIThisValue, ThisTy,
1003 for (FunctionArgList::const_iterator
i = Args.begin(), e = Args.end();
1011 if (
const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1012 Ty = PVD->getOriginalType();
1021 DI->EmitLocation(
Builder, StartLoc);
1027 LargestVectorWidth = VecWidth->getVectorWidth();
1032 if (
const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1044 llvm::BasicBlock *SkipCountBB =
nullptr;
1066 if (F->isInterposable())
return;
1068 for (llvm::BasicBlock &BB : *F)
1069 for (llvm::Instruction &I : BB)
1073 F->setDoesNotThrow();
1093 bool PassedParams =
true;
1095 if (
auto Inherited = CD->getInheritedConstructor())
1101 Args.push_back(Param);
1102 if (!Param->hasAttr<PassObjectSizeAttr>())
1106 getContext(), Param->getDeclContext(), Param->getLocation(),
1108 SizeArguments[Param] = Implicit;
1109 Args.push_back(Implicit);
1113 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1126 if (
const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1127 return !ClassDecl->hasTrivialDestructor();
1141 if (FD->
hasAttr<NoDebugAttr>())
1142 DebugInfo =
nullptr;
1148 BodyRange = Body->getSourceRange();
1151 CurEHLocation = BodyRange.
getEnd();
1163 if (SpecDecl->hasBody(SpecDecl))
1164 Loc = SpecDecl->getLocation();
1170 if (Body && ShouldEmitLifetimeMarkers)
1178 if (isa<CXXDestructorDecl>(FD))
1180 else if (isa<CXXConstructorDecl>(FD))
1184 FD->
hasAttr<CUDAGlobalAttr>())
1186 else if (isa<CXXMethodDecl>(FD) &&
1187 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1191 }
else if (FD->
isDefaulted() && isa<CXXMethodDecl>(FD) &&
1192 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1193 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1200 llvm_unreachable(
"no definition for emitted function");
1210 bool ShouldEmitUnreachable =
1216 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1217 SanitizerHandler::MissingReturn,
1219 }
else if (ShouldEmitUnreachable) {
1223 if (
SanOpts.
has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1225 Builder.ClearInsertionPoint();
1234 if (!
CurFn->doesNotThrow())
1243 if (!S)
return false;
1250 if (isa<LabelStmt>(S))
1255 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1259 if (isa<SwitchStmt>(S))
1260 IgnoreCaseStmts =
true;
1275 if (!S)
return false;
1279 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1283 if (isa<BreakStmt>(S))
1295 if (!S)
return false;
1301 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1302 isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1303 isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1304 isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1307 if (isa<DeclStmt>(S))
1323 llvm::APSInt ResultInt;
1327 ResultBool = ResultInt.getBoolValue();
1335 llvm::APSInt &ResultInt,
1358 llvm::BasicBlock *TrueBlock,
1359 llvm::BasicBlock *FalseBlock,
1360 uint64_t TrueCount) {
1363 if (
const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1366 if (CondBOp->getOpcode() == BO_LAnd) {
1369 bool ConstantBool =
false;
1412 if (CondBOp->getOpcode() == BO_LOr) {
1415 bool ConstantBool =
false;
1441 uint64_t RHSCount = TrueCount - LHSCount;
1463 if (
const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1465 if (CondUOp->getOpcode() == UO_LNot) {
1488 uint64_t LHSScaledTrueCount = 0;
1492 LHSScaledTrueCount = TrueCount * LHSRatio;
1501 LHSScaledTrueCount);
1508 TrueCount - LHSScaledTrueCount);
1514 if (
const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1527 llvm::MDNode *Unpredictable =
nullptr;
1530 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1531 if (FD && FD->
getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1533 Unpredictable = MDHelper.createUnpredictable();
1540 llvm::MDNode *Weights =
1541 createProfileWeights(TrueCount, CurrentCount - TrueCount);
1549 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1577 Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars,
"vla.end");
1579 llvm::BasicBlock *originBB = CGF.
Builder.GetInsertBlock();
1587 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2,
"vla.cur");
1588 cur->addIncoming(begin.getPointer(), originBB);
1599 Builder.CreateInBoundsGEP(CGF.
Int8Ty, cur, baseSizeInChars,
"vla.next");
1602 llvm::Value *done = Builder.CreateICmpEQ(next, end,
"vla-init.isdone");
1603 Builder.CreateCondBr(done, contBB, loopBB);
1604 cur->addIncoming(next, loopBB);
1614 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1633 dyn_cast_or_null<VariableArrayType>(
1636 SizeVal = VlaSize.NumElts;
1638 if (!eltSize.
isOne())
1659 llvm::GlobalVariable *NullVariable =
1660 new llvm::GlobalVariable(
CGM.
getModule(), NullConstant->getType(),
1662 llvm::GlobalVariable::PrivateLinkage,
1663 NullConstant, Twine());
1665 NullVariable->setAlignment(NullAlign.getQuantity());
1684 if (!IndirectBranch)
1690 IndirectBranch->addDestination(BB);
1691 return llvm::BlockAddress::get(
CurFn, BB);
1696 if (IndirectBranch)
return IndirectBranch->getParent();
1702 "indirect.goto.dest");
1705 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1706 return IndirectBranch->getParent();
1719 if (isa<VariableArrayType>(arrayType)) {
1730 baseType = elementType;
1731 return numVLAElements;
1733 }
while (isa<VariableArrayType>(arrayType));
1746 gepIndices.push_back(zero);
1748 uint64_t countFromCLAs = 1;
1751 llvm::ArrayType *llvmArrayType =
1753 while (llvmArrayType) {
1754 assert(isa<ConstantArrayType>(arrayType));
1755 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1756 == llvmArrayType->getNumElements());
1758 gepIndices.push_back(zero);
1759 countFromCLAs *= llvmArrayType->getNumElements();
1763 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1765 assert((!llvmArrayType || arrayType) &&
1766 "LLVM and Clang types are out-of-synch");
1775 cast<ConstantArrayType>(
arrayType)->getSize().getZExtValue();
1785 gepIndices,
"array.begin"),
1792 = llvm::ConstantInt::get(
SizeTy, countFromCLAs);
1796 numElements =
Builder.CreateNUWMul(numVLAElements, numElements);
1803 assert(vla &&
"type was not a variable array type!");
1816 assert(vlaSize &&
"no size for VLA!");
1817 assert(vlaSize->getType() ==
SizeTy);
1820 numElements = vlaSize;
1824 numElements =
Builder.CreateNUWMul(numElements, vlaSize);
1826 }
while ((type =
getContext().getAsVariableArrayType(elementType)));
1828 return { numElements, elementType };
1834 assert(vla &&
"type was not a variable array type!");
1841 assert(VlaSize &&
"no size for VLA!");
1842 assert(VlaSize->getType() ==
SizeTy);
1848 "Must pass variably modified type to EmitVLASizes!");
1858 switch (ty->getTypeClass()) {
1860 #define TYPE(Class, Base) 1861 #define ABSTRACT_TYPE(Class, Base) 1862 #define NON_CANONICAL_TYPE(Class, Base) 1863 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1864 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 1865 #include "clang/AST/TypeNodes.def" 1866 llvm_unreachable(
"unexpected dependent type!");
1872 case Type::ExtVector:
1875 case Type::Elaborated:
1876 case Type::TemplateSpecialization:
1877 case Type::ObjCTypeParam:
1878 case Type::ObjCObject:
1879 case Type::ObjCInterface:
1880 case Type::ObjCObjectPointer:
1881 llvm_unreachable(
"type class is never variably-modified!");
1883 case Type::Adjusted:
1884 type = cast<AdjustedType>(ty)->getAdjustedType();
1888 type = cast<DecayedType>(ty)->getPointeeType();
1892 type = cast<PointerType>(ty)->getPointeeType();
1895 case Type::BlockPointer:
1896 type = cast<BlockPointerType>(ty)->getPointeeType();
1899 case Type::LValueReference:
1900 case Type::RValueReference:
1901 type = cast<ReferenceType>(ty)->getPointeeType();
1904 case Type::MemberPointer:
1905 type = cast<MemberPointerType>(ty)->getPointeeType();
1908 case Type::ConstantArray:
1909 case Type::IncompleteArray:
1911 type = cast<ArrayType>(ty)->getElementType();
1914 case Type::VariableArray: {
1932 size->getType()->isSignedIntegerType()) {
1934 llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1935 llvm::Constant *StaticArgs[] = {
1939 SanitizerKind::VLABound),
1940 SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
1952 case Type::FunctionProto:
1953 case Type::FunctionNoProto:
1954 type = cast<FunctionType>(ty)->getReturnType();
1959 case Type::UnaryTransform:
1960 case Type::Attributed:
1961 case Type::SubstTemplateTypeParm:
1962 case Type::PackExpansion:
1963 case Type::MacroQualified:
1969 case Type::Decltype:
1971 case Type::DeducedTemplateSpecialization:
1975 case Type::TypeOfExpr:
1981 type = cast<AtomicType>(ty)->getValueType();
1985 type = cast<PipeType>(ty)->getElementType();
1992 if (
getContext().getBuiltinVaListType()->isArrayType())
2003 assert(Init.
hasValue() &&
"Invalid DeclRefExpr initializer!");
2006 Dbg->EmitGlobalVariable(E->
getDecl(), Init);
2021 llvm::Instruction *inst =
new llvm::BitCastInst(value, value->getType(),
"",
2025 protection.Inst = inst;
2030 if (!protection.Inst)
return;
2033 protection.Inst->eraseFromParent();
2042 llvm::Instruction *Assumption =
Builder.CreateAlignmentAssumption(
2046 OffsetValue, TheCheck, Assumption);
2056 llvm::Instruction *Assumption =
Builder.CreateAlignmentAssumption(
2061 OffsetValue, TheCheck, Assumption);
2070 if (
auto *CE = dyn_cast<CastExpr>(E))
2071 E = CE->getSubExprAsWritten();
2081 StringRef AnnotationStr,
2089 return Builder.CreateCall(AnnotationFn, Args);
2093 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
2104 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
2136 const llvm::Twine &Name,
2137 llvm::BasicBlock *BB,
2138 llvm::BasicBlock::iterator InsertPt)
const {
2145 llvm::Instruction *I,
const llvm::Twine &Name, llvm::BasicBlock *BB,
2146 llvm::BasicBlock::iterator InsertPt)
const {
2147 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
2154 std::string &FirstMissing) {
2156 if (ReqFeatures.empty())
2161 llvm::StringMap<bool> CallerFeatureMap;
2167 ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
2169 Feature.split(OrFeatures,
'|');
2170 return llvm::any_of(OrFeatures, [&](StringRef Feature) {
2171 if (!CallerFeatureMap.lookup(Feature)) {
2172 FirstMissing = Feature.str();
2205 std::string MissingFeature;
2208 const char *FeatureList =
2211 if (!FeatureList || StringRef(FeatureList) ==
"")
2213 StringRef(FeatureList).split(ReqFeatures,
',');
2219 }
else if (TargetDecl->
hasAttr<TargetAttr>() ||
2220 TargetDecl->
hasAttr<CPUSpecificAttr>()) {
2223 const TargetAttr *TD = TargetDecl->
getAttr<TargetAttr>();
2227 llvm::StringMap<bool> CalleeFeatureMap;
2230 for (
const auto &F : ParsedAttr.Features) {
2231 if (F[0] ==
'+' && CalleeFeatureMap.lookup(F.substr(1)))
2232 ReqFeatures.push_back(StringRef(F).substr(1));
2235 for (
const auto &F : CalleeFeatureMap) {
2238 ReqFeatures.push_back(F.getKey());
2250 llvm::IRBuilder<> IRB(
Builder.GetInsertBlock(),
Builder.GetInsertPoint());
2251 IRB.SetCurrentDebugLocation(
Builder.getCurrentDebugLocation());
2265 Condition ?
Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
2271 llvm::Function *Resolver,
2273 llvm::Function *FuncToReturn,
2274 bool SupportsIFunc) {
2275 if (SupportsIFunc) {
2276 Builder.CreateRet(FuncToReturn);
2281 llvm::for_each(Resolver->args(),
2282 [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
2284 llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2285 Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2287 if (Resolver->getReturnType()->isVoidTy())
2288 Builder.CreateRetVoid();
2290 Builder.CreateRet(Result);
2295 assert((
getContext().getTargetInfo().getTriple().getArch() ==
2296 llvm::Triple::x86 ||
2297 getContext().getTargetInfo().getTriple().getArch() ==
2298 llvm::Triple::x86_64) &&
2299 "Only implemented for x86 targets");
2305 Builder.SetInsertPoint(CurBlock);
2309 Builder.SetInsertPoint(CurBlock);
2310 llvm::Value *Condition = FormResolverCondition(RO);
2314 assert(&RO == Options.end() - 1 &&
2315 "Default or Generic case must be last");
2321 llvm::BasicBlock *RetBlock =
createBasicBlock(
"resolver_return", Resolver);
2326 Builder.CreateCondBr(Condition, RetBlock, CurBlock);
2330 Builder.SetInsertPoint(CurBlock);
2331 llvm::CallInst *TrapCall =
EmitTrapCall(llvm::Intrinsic::trap);
2332 TrapCall->setDoesNotReturn();
2333 TrapCall->setDoesNotThrow();
2335 Builder.ClearInsertionPoint();
2348 llvm::Instruction *Assumption) {
2349 assert(Assumption && isa<llvm::CallInst>(Assumption) &&
2350 cast<llvm::CallInst>(Assumption)->getCalledValue() ==
2351 llvm::Intrinsic::getDeclaration(
2352 Builder.GetInsertBlock()->getParent()->getParent(),
2353 llvm::Intrinsic::assume) &&
2354 "Assumption should be a call to llvm.assume().");
2355 assert(&(
Builder.GetInsertBlock()->back()) == Assumption &&
2356 "Assumption should be the last instruction of the basic block, " 2357 "since the basic block is still being generated.");
2369 Assumption->removeFromParent();
2375 OffsetValue =
Builder.getInt1(0);
2383 EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
2384 SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
2395 return DI->SourceLocToDebugLoc(Location);
2397 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
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...
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.
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)
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.
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
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.
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.
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...
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.
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.
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...
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...
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).
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.
TargetAttr::ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD)
Parses the target attributes passed in, and returns only the ones that are valid feature names...
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.
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.
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.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, GlobalDecl GD)
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.
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...
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.
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.
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
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...
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.
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...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.