本文整理汇总了C++中CharUnits类的典型用法代码示例。如果您正苦于以下问题:C++ CharUnits类的具体用法?C++ CharUnits怎么用?C++ CharUnits使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CharUnits类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: LookupFieldBitOffset
LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
const ObjCInterfaceDecl *OID,
llvm::Value *BaseValue,
const ObjCIvarDecl *Ivar,
unsigned CVRQualifiers,
llvm::Value *Offset) {
// Compute (type*) ( (char *) BaseValue + Offset)
QualType IvarTy = Ivar->getType();
llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, CGF.Int8PtrTy);
V = CGF.Builder.CreateInBoundsGEP(V, Offset, "add.ptr");
if (!Ivar->isBitField()) {
V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy);
LV.getQuals().addCVRQualifiers(CVRQualifiers);
return LV;
}
// We need to compute an access strategy for this bit-field. We are given the
// offset to the first byte in the bit-field, the sub-byte offset is taken
// from the original layout. We reuse the normal bit-field access strategy by
// treating this as an access to a struct where the bit-field is in byte 0,
// and adjust the containing type size as appropriate.
//
// FIXME: Note that currently we make a very conservative estimate of the
// alignment of the bit-field, because (a) it is not clear what guarantees the
// runtime makes us, and (b) we don't have a way to specify that the struct is
// at an alignment plus offset.
//
// Note, there is a subtle invariant here: we can only call this routine on
// non-synthesized ivars but we may be called for synthesized ivars. However,
// a synthesized ivar can never be a bit-field, so this is safe.
uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar);
uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();
uint64_t AlignmentBits = CGF.CGM.getContext().getTargetInfo().getCharAlign();
uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());
CharUnits StorageSize =
CGF.CGM.getContext().toCharUnitsFromBits(
llvm::RoundUpToAlignment(BitOffset + BitFieldSize, AlignmentBits));
CharUnits Alignment = CGF.CGM.getContext().toCharUnitsFromBits(AlignmentBits);
// Allocate a new CGBitFieldInfo object to describe this access.
//
// FIXME: This is incredibly wasteful, these should be uniqued or part of some
// layout object. However, this is blocked on other cleanups to the
// Objective-C code, so for now we just live with allocating a bunch of these
// objects.
CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
CGF.CGM.getContext().toBits(StorageSize),
Alignment.getQuantity()));
V = CGF.Builder.CreateBitCast(V,
llvm::Type::getIntNPtrTy(CGF.getLLVMContext(),
Info->StorageSize));
return LValue::MakeBitfield(V, *Info,
IvarTy.withCVRQualifiers(CVRQualifiers),
Alignment);
}
示例2: assert
void SlicingCheck::check(const MatchFinder::MatchResult &Result) {
const auto *BaseDecl = Result.Nodes.getNodeAs<CXXRecordDecl>("BaseDecl");
const auto *DerivedDecl =
Result.Nodes.getNodeAs<CXXRecordDecl>("DerivedDecl");
const auto *Call = Result.Nodes.getNodeAs<Expr>("Call");
assert(BaseDecl != nullptr);
assert(DerivedDecl != nullptr);
assert(Call != nullptr);
// Warn when slicing the vtable.
// We're looking through all the methods in the derived class and see if they
// override some methods in the base class.
// It's not enough to just test whether the class is polymorphic because we
// would be fine slicing B to A if no method in B (or its bases) overrides
// anything in A:
// class A { virtual void f(); };
// class B : public A {};
// because in that case calling A::f is the same as calling B::f.
DiagnoseSlicedOverriddenMethods(*Call, *DerivedDecl, *BaseDecl);
// Warn when slicing member variables.
const auto &BaseLayout =
BaseDecl->getASTContext().getASTRecordLayout(BaseDecl);
const auto &DerivedLayout =
DerivedDecl->getASTContext().getASTRecordLayout(DerivedDecl);
const CharUnits StateSize =
DerivedLayout.getDataSize() - BaseLayout.getDataSize();
if (StateSize.isPositive()) {
diag(Call->getExprLoc(), "slicing object from type %0 to %1 discards "
"%2 bytes of state")
<< DerivedDecl << BaseDecl << static_cast<int>(StateSize.getQuantity());
}
}
示例3: VisitUnaryExprOrTypeTraitExpr
void ExprEngine::
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
ExplodedNode *Pred,
ExplodedNodeSet &Dst) {
StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
QualType T = Ex->getTypeOfArgument();
if (Ex->getKind() == UETT_SizeOf) {
if (!T->isIncompleteType() && !T->isConstantSizeType()) {
assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
// FIXME: Add support for VLA type arguments and VLA expressions.
// When that happens, we should probably refactor VLASizeChecker's code.
return;
}
else if (T->getAs<ObjCObjectType>()) {
// Some code tries to take the sizeof an ObjCObjectType, relying that
// the compiler has laid out its representation. Just report Unknown
// for these.
return;
}
}
APSInt Value = Ex->EvaluateKnownConstInt(getContext());
CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
ProgramStateRef state = Pred->getState();
state = state->BindExpr(Ex, Pred->getLocationContext(),
svalBuilder.makeIntVal(amt.getQuantity(),
Ex->getType()));
Bldr.generateNode(Ex, Pred, state);
}
示例4: addLegalTypedData
void SwiftAggLowering::addLegalTypedData(llvm::Type *type,
CharUnits begin, CharUnits end) {
// Require the type to be naturally aligned.
if (!begin.isZero() && !begin.isMultipleOf(getNaturalAlignment(CGM, type))) {
// Try splitting vector types.
if (auto vecTy = dyn_cast<llvm::VectorType>(type)) {
auto split = splitLegalVectorType(CGM, end - begin, vecTy);
auto eltTy = split.first;
auto numElts = split.second;
auto eltSize = (end - begin) / numElts;
assert(eltSize == getTypeStoreSize(CGM, eltTy));
for (size_t i = 0, e = numElts; i != e; ++i) {
addLegalTypedData(eltTy, begin, begin + eltSize);
begin += eltSize;
}
assert(begin == end);
return;
}
return addOpaqueData(begin, end);
}
addEntry(type, begin, end);
}
示例5:
llvm::Type *
CGRecordLayoutBuilder::LayoutUnionField(const FieldDecl *Field,
const ASTRecordLayout &Layout) {
Fields[Field] = 0;
if (Field->isBitField()) {
uint64_t FieldSize = Field->getBitWidthValue(Types.getContext());
// Ignore zero sized bit fields.
if (FieldSize == 0)
return 0;
unsigned StorageBits = llvm::RoundUpToAlignment(
FieldSize, Types.getTarget().getCharAlign());
CharUnits NumBytesToAppend
= Types.getContext().toCharUnitsFromBits(StorageBits);
llvm::Type *FieldTy = llvm::Type::getInt8Ty(Types.getLLVMContext());
if (NumBytesToAppend > CharUnits::One())
FieldTy = llvm::ArrayType::get(FieldTy, NumBytesToAppend.getQuantity());
// Add the bit field info.
BitFields[Field] = CGBitFieldInfo::MakeInfo(Types, Field, 0, FieldSize,
StorageBits,
Alignment.getQuantity());
return FieldTy;
}
// This is a regular union field.
return Types.ConvertTypeForMem(Field->getType());
}
示例6: assert
void CGRecordLowering::insertPadding() {
std::vector<std::pair<CharUnits, CharUnits> > Padding;
CharUnits Size = CharUnits::Zero();
for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
MemberEnd = Members.end();
Member != MemberEnd; ++Member) {
if (!Member->Data)
continue;
CharUnits Offset = Member->Offset;
assert(Offset >= Size);
// Insert padding if we need to.
if (Offset !=
Size.alignTo(Packed ? CharUnits::One() : getAlignment(Member->Data)))
Padding.push_back(std::make_pair(Size, Offset - Size));
Size = Offset + getSize(Member->Data);
}
if (Padding.empty())
return;
// Add the padding to the Members list and sort it.
for (std::vector<std::pair<CharUnits, CharUnits> >::const_iterator
Pad = Padding.begin(), PadEnd = Padding.end();
Pad != PadEnd; ++Pad)
Members.push_back(StorageInfo(Pad->first, getByteArrayType(Pad->second)));
std::stable_sort(Members.begin(), Members.end());
}
示例7: assert
llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
llvm::Value *NewPtr,
llvm::Value *NumElements,
const CXXNewExpr *expr,
QualType ElementType) {
assert(NeedsArrayCookie(expr));
unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
ASTContext &Ctx = getContext();
QualType SizeTy = Ctx.getSizeType();
CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
// The size of the cookie.
CharUnits CookieSize =
std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
// Compute an offset to the cookie.
llvm::Value *CookiePtr = NewPtr;
CharUnits CookieOffset = CookieSize - SizeSize;
if (!CookieOffset.isZero())
CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
CookieOffset.getQuantity());
// Write the number of elements into the appropriate slot.
llvm::Value *NumElementsPtr
= CGF.Builder.CreateBitCast(CookiePtr,
CGF.ConvertType(SizeTy)->getPointerTo(AS));
CGF.Builder.CreateStore(NumElements, NumElementsPtr);
// Finally, compute a pointer to the actual data buffer by skipping
// over the cookie completely.
return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
CookieSize.getQuantity());
}
示例8: while
RegionOffset MemRegion::getAsOffset() const {
const MemRegion *R = this;
int64_t Offset = 0;
while (1) {
switch (R->getKind()) {
default:
return RegionOffset(0);
case SymbolicRegionKind:
case AllocaRegionKind:
case CompoundLiteralRegionKind:
case CXXThisRegionKind:
case StringRegionKind:
case VarRegionKind:
case CXXTempObjectRegionKind:
goto Finish;
case ElementRegionKind: {
const ElementRegion *ER = cast<ElementRegion>(R);
QualType EleTy = ER->getValueType();
if (!IsCompleteType(getContext(), EleTy))
return RegionOffset(0);
SVal Index = ER->getIndex();
if (const nonloc::ConcreteInt *CI=dyn_cast<nonloc::ConcreteInt>(&Index)) {
int64_t i = CI->getValue().getSExtValue();
CharUnits Size = getContext().getTypeSizeInChars(EleTy);
Offset += i * Size.getQuantity() * 8;
} else {
// We cannot compute offset for non-concrete index.
return RegionOffset(0);
}
R = ER->getSuperRegion();
break;
}
case FieldRegionKind: {
const FieldRegion *FR = cast<FieldRegion>(R);
const RecordDecl *RD = FR->getDecl()->getParent();
if (!RD->isCompleteDefinition())
// We cannot compute offset for incomplete type.
return RegionOffset(0);
// Get the field number.
unsigned idx = 0;
for (RecordDecl::field_iterator FI = RD->field_begin(),
FE = RD->field_end(); FI != FE; ++FI, ++idx)
if (FR->getDecl() == *FI)
break;
const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
// This is offset in bits.
Offset += Layout.getFieldOffset(idx);
R = FR->getSuperRegion();
break;
}
}
}
Finish:
return RegionOffset(R, Offset);
}
示例9: getSetupArgumentFn
void CGNVCUDARuntime::emitDeviceStubBodyLegacy(CodeGenFunction &CGF,
FunctionArgList &Args) {
// Emit a call to cudaSetupArgument for each arg in Args.
llvm::FunctionCallee cudaSetupArgFn = getSetupArgumentFn();
llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
CharUnits Offset = CharUnits::Zero();
for (const VarDecl *A : Args) {
CharUnits TyWidth, TyAlign;
std::tie(TyWidth, TyAlign) =
CGM.getContext().getTypeInfoInChars(A->getType());
Offset = Offset.alignTo(TyAlign);
llvm::Value *Args[] = {
CGF.Builder.CreatePointerCast(CGF.GetAddrOfLocalVar(A).getPointer(),
VoidPtrTy),
llvm::ConstantInt::get(SizeTy, TyWidth.getQuantity()),
llvm::ConstantInt::get(SizeTy, Offset.getQuantity()),
};
llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(cudaSetupArgFn, Args);
llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);
llvm::Value *CBZero = CGF.Builder.CreateICmpEQ(CB, Zero);
llvm::BasicBlock *NextBlock = CGF.createBasicBlock("setup.next");
CGF.Builder.CreateCondBr(CBZero, NextBlock, EndBlock);
CGF.EmitBlock(NextBlock);
Offset += TyWidth;
}
// Emit the call to cudaLaunch
llvm::FunctionCallee cudaLaunchFn = getLaunchFn();
llvm::Value *Arg = CGF.Builder.CreatePointerCast(CGF.CurFn, CharPtrTy);
CGF.EmitRuntimeCallOrInvoke(cudaLaunchFn, Arg);
CGF.EmitBranch(EndBlock);
CGF.EmitBlock(EndBlock);
}
示例10: getZeroInt
// Returns an adjusted base cast to i8*, since we do more address arithmetic on
// it.
llvm::Value *
MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
const CXXRecordDecl *RD, llvm::Value *Base,
llvm::Value *VirtualBaseAdjustmentOffset,
llvm::Value *VBPtrOffset) {
CGBuilderTy &Builder = CGF.Builder;
Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
llvm::BasicBlock *OriginalBB = 0;
llvm::BasicBlock *SkipAdjustBB = 0;
llvm::BasicBlock *VBaseAdjustBB = 0;
// In the unspecified inheritance model, there might not be a vbtable at all,
// in which case we need to skip the virtual base lookup. If there is a
// vbtable, the first entry is a no-op entry that gives back the original
// base, so look for a virtual base adjustment offset of zero.
if (VBPtrOffset) {
OriginalBB = Builder.GetInsertBlock();
VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
llvm::Value *IsVirtual =
Builder.CreateICmpNE(VirtualBaseAdjustmentOffset, getZeroInt(),
"memptr.is_vbase");
Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
CGF.EmitBlock(VBaseAdjustBB);
}
// If we weren't given a dynamic vbptr offset, RD should be complete and we'll
// know the vbptr offset.
if (!VBPtrOffset) {
CharUnits offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
}
// Load the vbtable pointer from the vbtable offset in the instance.
llvm::Value *VBPtr =
Builder.CreateInBoundsGEP(Base, VBPtrOffset, "memptr.vbptr");
llvm::Value *VBTable =
Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
VBTable = Builder.CreateLoad(VBTable, "memptr.vbtable");
// Load an i32 offset from the vb-table.
llvm::Value *VBaseOffs =
Builder.CreateInBoundsGEP(VBTable, VirtualBaseAdjustmentOffset);
VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
VBaseOffs = Builder.CreateLoad(VBaseOffs, "memptr.vbase_offs");
// Add it to VBPtr. GEP will sign extend the i32 value for us.
llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
// Merge control flow with the case where we didn't have to adjust.
if (VBaseAdjustBB) {
Builder.CreateBr(SkipAdjustBB);
CGF.EmitBlock(SkipAdjustBB);
llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
Phi->addIncoming(Base, OriginalBB);
Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
return Phi;
}
return AdjustedBase;
}
示例11: checkPreStmt
void CastSizeChecker::checkPreStmt(const CastExpr *CE,CheckerContext &C) const {
const Expr *E = CE->getSubExpr();
ASTContext &Ctx = C.getASTContext();
QualType ToTy = Ctx.getCanonicalType(CE->getType());
const PointerType *ToPTy = dyn_cast<PointerType>(ToTy.getTypePtr());
if (!ToPTy)
return;
QualType ToPointeeTy = ToPTy->getPointeeType();
// Only perform the check if 'ToPointeeTy' is a complete type.
if (ToPointeeTy->isIncompleteType())
return;
ProgramStateRef state = C.getState();
const MemRegion *R = state->getSVal(E, C.getLocationContext()).getAsRegion();
if (!R)
return;
const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
if (!SR)
return;
SValBuilder &svalBuilder = C.getSValBuilder();
SVal extent = SR->getExtent(svalBuilder);
const llvm::APSInt *extentInt = svalBuilder.getKnownValue(state, extent);
if (!extentInt)
return;
CharUnits regionSize = CharUnits::fromQuantity(extentInt->getSExtValue());
CharUnits typeSize = C.getASTContext().getTypeSizeInChars(ToPointeeTy);
// Ignore void, and a few other un-sizeable types.
if (typeSize.isZero())
return;
if (regionSize % typeSize == 0)
return;
if (evenFlexibleArraySize(Ctx, regionSize, typeSize, ToPointeeTy))
return;
if (ExplodedNode *errorNode = C.generateErrorNode()) {
if (!BT)
BT.reset(new BuiltinBug(this, "Cast region with wrong size.",
"Cast a region whose size is not a multiple"
" of the destination type size."));
auto R = llvm::make_unique<BugReport>(*BT, BT->getDescription(), errorNode);
R->addRange(CE->getSourceRange());
C.emitReport(std::move(R));
}
}
示例12: getDesugaredValueType
DefinedOrUnknownSVal TypedValueRegion::getExtent(SValBuilder &svalBuilder) const {
ASTContext &Ctx = svalBuilder.getContext();
QualType T = getDesugaredValueType(Ctx);
if (isa<VariableArrayType>(T))
return nonloc::SymbolVal(svalBuilder.getSymbolManager().getExtentSymbol(this));
if (isa<IncompleteArrayType>(T))
return UnknownVal();
CharUnits size = Ctx.getTypeSizeInChars(T);
QualType sizeTy = svalBuilder.getArrayIndexType();
return svalBuilder.makeIntVal(size.getQuantity(), sizeTy);
}
示例13: scaleValue
// Scale a base value by a scaling factor, and return the scaled
// value as an SVal. Used by 'computeOffset'.
static inline SVal scaleValue(ProgramStateRef state,
NonLoc baseVal, CharUnits scaling,
SValBuilder &sb) {
return sb.evalBinOpNN(state, BO_Mul, baseVal,
sb.makeArrayIndex(scaling.getQuantity()),
sb.getArrayIndexType());
}
示例14: AppendBytes
void CGRecordLayoutBuilder::AppendBytes(CharUnits numBytes) {
if (numBytes.isZero())
return;
// Append the padding field
AppendField(NextFieldOffset, getByteArrayType(numBytes));
}
示例15: PreVisitCastExpr
void CastSizeChecker::PreVisitCastExpr(CheckerContext &C, const CastExpr *CE) {
const Expr *E = CE->getSubExpr();
ASTContext &Ctx = C.getASTContext();
QualType ToTy = Ctx.getCanonicalType(CE->getType());
PointerType *ToPTy = dyn_cast<PointerType>(ToTy.getTypePtr());
if (!ToPTy)
return;
QualType ToPointeeTy = ToPTy->getPointeeType();
const GRState *state = C.getState();
const MemRegion *R = state->getSVal(E).getAsRegion();
if (R == 0)
return;
const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
if (SR == 0)
return;
ValueManager &ValMgr = C.getValueManager();
SVal Extent = SR->getExtent(ValMgr);
SValuator &SVator = ValMgr.getSValuator();
const llvm::APSInt *ExtentInt = SVator.getKnownValue(state, Extent);
if (!ExtentInt)
return;
CharUnits RegionSize = CharUnits::fromQuantity(ExtentInt->getSExtValue());
CharUnits TypeSize = C.getASTContext().getTypeSizeInChars(ToPointeeTy);
// Ignore void, and a few other un-sizeable types.
if (TypeSize.isZero())
return;
if (RegionSize % TypeSize != 0) {
if (ExplodedNode *N = C.GenerateSink()) {
if (!BT)
BT = new BuiltinBug("Cast region with wrong size.",
"Cast a region whose size is not a multiple of the"
" destination type size.");
RangedBugReport *R = new RangedBugReport(*BT, BT->getDescription(), N);
R->addRange(CE->getSourceRange());
C.EmitReport(R);
}
}
}