1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
|
//===-- classes.cpp -------------------------------------------------------===//
//
// LDC – the LLVM D compiler
//
// This file is distributed under the BSD-style LDC license. See the LICENSE
// file for details.
//
//===----------------------------------------------------------------------===//
#include "gen/classes.h"
#include "dmd/aggregate.h"
#include "dmd/declaration.h"
#include "dmd/errors.h"
#include "dmd/expression.h"
#include "dmd/identifier.h"
#include "dmd/init.h"
#include "dmd/mtype.h"
#include "dmd/target.h"
#include "gen/arrays.h"
#include "gen/dvalue.h"
#include "gen/functions.h"
#include "gen/irstate.h"
#include "gen/llvm.h"
#include "gen/llvmhelpers.h"
#include "gen/logger.h"
#include "gen/nested.h"
#include "gen/optimizer.h"
#include "gen/runtime.h"
#include "gen/structs.h"
#include "gen/tollvm.h"
#include "ir/iraggr.h"
#include "ir/irdsymbol.h"
#include "ir/irfunction.h"
#include "ir/irtypeclass.h"
////////////////////////////////////////////////////////////////////////////////
// FIXME: this needs to be cleaned up
void DtoResolveClass(ClassDeclaration *cd) {
if (cd->ir->isResolved()) {
return;
}
cd->ir->setResolved();
IF_LOG Logger::println("DtoResolveClass(%s): %s", cd->toPrettyChars(),
cd->loc.toChars());
LOG_SCOPE;
// make sure the base classes are processed first
for (auto bc : *cd->baseclasses) {
DtoResolveClass(bc->sym);
}
// make sure type exists
DtoType(cd->type);
// create IrAggr
getIrAggr(cd, true);
// make sure all fields really get their ir field
for (auto vd : cd->fields) {
IF_LOG {
if (isIrFieldCreated(vd)) {
Logger::println("class field already exists");
}
}
getIrField(vd, true);
}
}
////////////////////////////////////////////////////////////////////////////////
DValue *DtoNewClass(const Loc &loc, TypeClass *tc, NewExp *newexp) {
// resolve type
DtoResolveClass(tc->sym);
// allocate
LLValue *mem;
bool doInit = true;
if (newexp->onstack) {
mem = DtoRawAlloca(DtoType(tc)->getContainedType(0), tc->sym->alignsize,
".newclass_alloca");
} else {
const bool useEHAlloc = global.params.ehnogc && newexp->thrownew;
llvm::Function *fn = getRuntimeFunction(
loc, gIR->module, useEHAlloc ? "_d_newThrowable" : "_d_allocclass");
LLConstant *ci = DtoBitCast(getIrAggr(tc->sym)->getClassInfoSymbol(),
DtoType(getClassInfoType()));
mem = gIR->CreateCallOrInvoke(
fn, ci, useEHAlloc ? ".newthrowable_alloc" : ".newclass_gc_alloc");
mem = DtoBitCast(mem, DtoType(tc),
useEHAlloc ? ".newthrowable" : ".newclass_gc");
doInit = !useEHAlloc;
}
// init
if (doInit)
DtoInitClass(tc, mem);
// init inner-class outer reference
if (newexp->thisexp) {
Logger::println("Resolving outer class");
LOG_SCOPE;
unsigned idx = getFieldGEPIndex(tc->sym, tc->sym->vthis);
LLValue *src = DtoRVal(newexp->thisexp);
LLValue *dst = DtoGEP(mem, 0, idx);
IF_LOG Logger::cout() << "dst: " << *dst << "\nsrc: " << *src << '\n';
DtoStore(src, DtoBitCast(dst, getPtrToType(src->getType())));
}
// set the context for nested classes
else if (tc->sym->isNested() && tc->sym->vthis) {
DtoResolveNestedContext(loc, tc->sym, mem);
}
// call constructor
if (newexp->member) {
// evaluate argprefix
if (newexp->argprefix) {
toElemDtor(newexp->argprefix);
}
Logger::println("Calling constructor");
assert(newexp->arguments != NULL);
DFuncValue dfn(newexp->member, DtoCallee(newexp->member), mem);
// ignore ctor return value (C++ ctors on Posix may not return `this`)
DtoCallFunction(newexp->loc, tc, &dfn, newexp->arguments);
return new DImValue(tc, mem);
}
assert(newexp->argprefix == NULL);
// return default constructed class
return new DImValue(tc, mem);
}
////////////////////////////////////////////////////////////////////////////////
void DtoInitClass(TypeClass *tc, LLValue *dst) {
DtoResolveClass(tc->sym);
IrClass *irClass = getIrAggr(tc->sym);
// Set vtable field. Doing this seperately might be optimized better.
LLValue *tmp = DtoGEP(dst, 0u, 0, "vtbl");
LLValue *val =
DtoBitCast(irClass->getVtblSymbol(), tmp->getType()->getContainedType(0));
DtoStore(val, tmp);
// For D classes, set the monitor field to null.
const bool isCPPclass = tc->sym->isCPPclass() ? true : false;
if (!isCPPclass) {
tmp = DtoGEP(dst, 0, 1, "monitor");
val = LLConstant::getNullValue(tmp->getType()->getContainedType(0));
DtoStore(val, tmp);
}
// Copy the rest from the static initializer, if any.
unsigned const firstDataIdx = isCPPclass ? 1 : 2;
uint64_t const dataBytes =
tc->sym->structsize - target.ptrsize * firstDataIdx;
if (dataBytes == 0) {
return;
}
LLValue *dstarr = DtoGEP(dst, 0, firstDataIdx);
// init symbols might not have valid types
LLValue *initsym = irClass->getInitSymbol();
initsym = DtoBitCast(initsym, DtoType(tc));
LLValue *srcarr = DtoGEP(initsym, 0, firstDataIdx);
DtoMemCpy(dstarr, srcarr, DtoConstSize_t(dataBytes));
}
////////////////////////////////////////////////////////////////////////////////
void DtoFinalizeClass(const Loc &loc, LLValue *inst) {
// get runtime function
llvm::Function *fn =
getRuntimeFunction(loc, gIR->module, "_d_callfinalizer");
gIR->CreateCallOrInvoke(
fn, DtoBitCast(inst, fn->getFunctionType()->getParamType(0)), "");
}
////////////////////////////////////////////////////////////////////////////////
void DtoFinalizeScopeClass(const Loc &loc, LLValue *inst, bool hasDtor) {
if (!isOptimizationEnabled() || hasDtor) {
DtoFinalizeClass(loc, inst);
return;
}
// no dtors => only finalize (via druntime call) if monitor is set,
// see https://github.com/ldc-developers/ldc/issues/2515
llvm::BasicBlock *ifbb = gIR->insertBB("if");
llvm::BasicBlock *endbb = gIR->insertBBAfter(ifbb, "endif");
const auto monitor = DtoLoad(DtoGEP(inst, 0, 1), ".monitor");
const auto hasMonitor =
gIR->ir->CreateICmp(llvm::CmpInst::ICMP_NE, monitor,
getNullValue(monitor->getType()), ".hasMonitor");
llvm::BranchInst::Create(ifbb, endbb, hasMonitor, gIR->scopebb());
gIR->ir->SetInsertPoint(ifbb);
DtoFinalizeClass(loc, inst);
gIR->ir->CreateBr(endbb);
gIR->ir->SetInsertPoint(endbb);
}
////////////////////////////////////////////////////////////////////////////////
DValue *DtoCastClass(const Loc &loc, DValue *val, Type *_to) {
IF_LOG Logger::println("DtoCastClass(%s, %s)", val->type->toChars(),
_to->toChars());
LOG_SCOPE;
Type *to = _to->toBasetype();
// class -> pointer
if (to->ty == TY::Tpointer) {
IF_LOG Logger::println("to pointer");
LLType *tolltype = DtoType(_to);
LLValue *rval = DtoBitCast(DtoRVal(val), tolltype);
return new DImValue(_to, rval);
}
// class -> bool
if (to->ty == TY::Tbool) {
IF_LOG Logger::println("to bool");
LLValue *llval = DtoRVal(val);
LLValue *zero = LLConstant::getNullValue(llval->getType());
return new DImValue(_to, gIR->ir->CreateICmpNE(llval, zero));
}
// class -> integer
if (to->isintegral()) {
IF_LOG Logger::println("to %s", to->toChars());
// get class ptr
LLValue *v = DtoRVal(val);
// cast to size_t
v = gIR->ir->CreatePtrToInt(v, DtoSize_t(), "");
// cast to the final int type
DImValue im(Type::tsize_t, v);
return DtoCastInt(loc, &im, _to);
}
// class -> typeof(null)
if (to->ty == TY::Tnull) {
IF_LOG Logger::println("to %s", to->toChars());
return new DImValue(_to, LLConstant::getNullValue(DtoType(_to)));
}
// must be class/interface
assert(to->ty == TY::Tclass);
TypeClass *tc = static_cast<TypeClass *>(to);
// from type
Type *from = val->type->toBasetype();
TypeClass *fc = static_cast<TypeClass *>(from);
// copy DMD logic:
// if to isBaseOf from with offset: (to ? to + offset : null)
// else if from is C++ and to is C++: to
// else if from is C++ and to is D: null
// else if from is interface: _d_interface_cast(to)
// else if from is class: _d_dynamic_cast(to)
LLType *toType = DtoType(_to);
int offset = 0;
if (tc->sym->isBaseOf(fc->sym, &offset)) {
Logger::println("static down cast");
// interface types don't cover the full object in case of multiple inheritence
// so GEP on the original type is inappropriate
// offset pointer
LLValue *orig = DtoRVal(val);
LLValue *v = orig;
if (offset != 0) {
assert(offset > 0);
v = DtoBitCast(v, getVoidPtrType());
v = DtoGEP1(v, DtoConstUint(offset));
}
IF_LOG {
Logger::cout() << "V = " << *v << std::endl;
Logger::cout() << "T = " << *toType << std::endl;
}
v = DtoBitCast(v, toType);
// Check whether the original value was null, and return null if so.
// Sure we could have jumped over the code above in this case, but
// it's just a GEP and (maybe) a pointer-to-pointer BitCast, so it
// should be pretty cheap and perfectly safe even if the original was
// null.
LLValue *isNull = gIR->ir->CreateICmpEQ(
orig, LLConstant::getNullValue(orig->getType()), ".nullcheck");
v = gIR->ir->CreateSelect(isNull, LLConstant::getNullValue(toType), v,
".interface");
// return r-value
return new DImValue(_to, v);
}
if (fc->sym->classKind == ClassKind::cpp) {
Logger::println("C++ class/interface cast");
LLValue *v = tc->sym->classKind == ClassKind::cpp
? DtoBitCast(DtoRVal(val), toType)
: LLConstant::getNullValue(toType);
return new DImValue(_to, v);
}
// from interface
if (fc->sym->isInterfaceDeclaration()) {
Logger::println("interface cast");
return DtoDynamicCastInterface(loc, val, _to);
}
// from class
Logger::println("dynamic up cast");
return DtoDynamicCastObject(loc, val, _to);
}
////////////////////////////////////////////////////////////////////////////////
static void resolveObjectAndClassInfoClasses() {
// check declarations in object.d
getObjectType();
getClassInfoType();
DtoResolveClass(ClassDeclaration::object);
DtoResolveClass(Type::typeinfoclass);
}
DValue *DtoDynamicCastObject(const Loc &loc, DValue *val, Type *_to) {
// call:
// Object _d_dynamic_cast(Object o, ClassInfo c)
llvm::Function *func =
getRuntimeFunction(loc, gIR->module, "_d_dynamic_cast");
LLFunctionType *funcTy = func->getFunctionType();
resolveObjectAndClassInfoClasses();
// Object o
LLValue *obj = DtoRVal(val);
obj = DtoBitCast(obj, funcTy->getParamType(0));
assert(funcTy->getParamType(0) == obj->getType());
// ClassInfo c
TypeClass *to = static_cast<TypeClass *>(_to->toBasetype());
DtoResolveClass(to->sym);
LLValue *cinfo = getIrAggr(to->sym)->getClassInfoSymbol();
// unfortunately this is needed as the implementation of object differs
// somehow from the declaration
// this could happen in user code as well :/
cinfo = DtoBitCast(cinfo, funcTy->getParamType(1));
assert(funcTy->getParamType(1) == cinfo->getType());
// call it
LLValue *ret = gIR->CreateCallOrInvoke(func, obj, cinfo);
// cast return value
ret = DtoBitCast(ret, DtoType(_to));
return new DImValue(_to, ret);
}
////////////////////////////////////////////////////////////////////////////////
DValue *DtoDynamicCastInterface(const Loc &loc, DValue *val, Type *_to) {
// call:
// Object _d_interface_cast(void* p, ClassInfo c)
llvm::Function *func =
getRuntimeFunction(loc, gIR->module, "_d_interface_cast");
LLFunctionType *funcTy = func->getFunctionType();
resolveObjectAndClassInfoClasses();
// void* p
LLValue *ptr = DtoRVal(val);
ptr = DtoBitCast(ptr, funcTy->getParamType(0));
// ClassInfo c
TypeClass *to = static_cast<TypeClass *>(_to->toBasetype());
DtoResolveClass(to->sym);
LLValue *cinfo = getIrAggr(to->sym)->getClassInfoSymbol();
// unfortunately this is needed as the implementation of object differs
// somehow from the declaration
// this could happen in user code as well :/
cinfo = DtoBitCast(cinfo, funcTy->getParamType(1));
// call it
LLValue *ret = gIR->CreateCallOrInvoke(func, ptr, cinfo);
// cast return value
ret = DtoBitCast(ret, DtoType(_to));
return new DImValue(_to, ret);
}
////////////////////////////////////////////////////////////////////////////////
LLValue *DtoVirtualFunctionPointer(DValue *inst, FuncDeclaration *fdecl) {
// sanity checks
assert(fdecl->isVirtual());
assert(!fdecl->isFinalFunc());
assert(inst->type->toBasetype()->ty == TY::Tclass);
// slot 0 is always ClassInfo/Interface* unless it is a CPP class
assert(fdecl->vtblIndex > 0 ||
(fdecl->vtblIndex == 0 &&
inst->type->toBasetype()->isTypeClass()->sym->isCPPclass()));
// get instance
LLValue *vthis = DtoRVal(inst);
IF_LOG Logger::cout() << "vthis: " << *vthis << '\n';
LLValue *funcval = vthis;
// get the vtbl for objects
funcval = DtoGEP(funcval, 0u, 0);
// load vtbl ptr
funcval = DtoLoad(funcval);
// index vtbl
const std::string name = fdecl->toChars();
const auto vtblname = name + "@vtbl";
funcval = DtoGEP(funcval, 0, fdecl->vtblIndex, vtblname.c_str());
// load opaque pointer
funcval = DtoAlignedLoad(funcval);
IF_LOG Logger::cout() << "funcval: " << *funcval << '\n';
// cast to funcptr type
funcval = DtoBitCast(funcval, getPtrToType(DtoFunctionType(fdecl)));
// postpone naming until after casting to get the name in call instructions
funcval->setName(name);
IF_LOG Logger::cout() << "funcval casted: " << *funcval << '\n';
return funcval;
}
|