Mercurial > projects > ldc
annotate gen/toobj.c @ 8:5e69b77a5c51 trunk
[svn r12] fixed accessing aggregate fields of aggregates
removed some useless branches for successive scopes ala {}{}{}
author | lindquist |
---|---|
date | Thu, 27 Sep 2007 06:03:06 +0200 |
parents | 35d93ce68cf4 |
children | dafae18f9c08 |
rev | line source |
---|---|
1 | 1 |
2 // Copyright (c) 1999-2004 by Digital Mars | |
3 // All Rights Reserved | |
4 // written by Walter Bright | |
5 // www.digitalmars.com | |
6 // License for redistribution is by either the Artistic License | |
7 // in artistic.txt, or the GNU General Public License in gnu.txt. | |
8 // See the included readme.txt for details. | |
9 | |
10 #include <cstddef> | |
11 #include <iostream> | |
12 #include <fstream> | |
13 | |
14 #include "llvm/Type.h" | |
15 #include "llvm/Constants.h" | |
16 #include "llvm/DerivedTypes.h" | |
17 #include "llvm/Instructions.h" | |
18 #include "llvm/Analysis/Verifier.h" | |
19 #include "llvm/Bitcode/ReaderWriter.h" | |
20 | |
21 #include "llvm/Target/TargetData.h" | |
22 #include "llvm/Target/TargetMachine.h" | |
23 #include "llvm/Target/TargetMachineRegistry.h" | |
24 | |
25 #include "mars.h" | |
26 #include "module.h" | |
27 #include "mtype.h" | |
28 #include "declaration.h" | |
29 #include "statement.h" | |
30 #include "enum.h" | |
31 #include "aggregate.h" | |
32 #include "init.h" | |
33 #include "attrib.h" | |
34 #include "id.h" | |
35 #include "import.h" | |
36 #include "template.h" | |
37 | |
4
e116aa1488e6
[svn r8] changed backend includes to always use the gen/<foo>.h prefix
lindquist
parents:
1
diff
changeset
|
38 #include "gen/irstate.h" |
e116aa1488e6
[svn r8] changed backend includes to always use the gen/<foo>.h prefix
lindquist
parents:
1
diff
changeset
|
39 #include "gen/elem.h" |
e116aa1488e6
[svn r8] changed backend includes to always use the gen/<foo>.h prefix
lindquist
parents:
1
diff
changeset
|
40 #include "gen/logger.h" |
e116aa1488e6
[svn r8] changed backend includes to always use the gen/<foo>.h prefix
lindquist
parents:
1
diff
changeset
|
41 #include "gen/tollvm.h" |
1 | 42 |
43 ////////////////////////////////////////////////////////////////////////////////////////// | |
44 | |
45 void | |
46 Module::genobjfile() | |
47 { | |
48 Logger::cout() << "Generating module: " << (md ? md->toChars() : toChars()) << '\n'; | |
49 LOG_SCOPE; | |
50 | |
6 | 51 // start by deleting the old object file |
1 | 52 deleteObjFile(); |
53 | |
6 | 54 // creaet a new ir state |
1 | 55 IRState ir; |
56 gIR = &ir; | |
57 ir.dmodule = this; | |
58 | |
6 | 59 // name the module |
1 | 60 std::string mname(toChars()); |
61 if (md != 0) | |
62 mname = md->toChars(); | |
63 ir.module = new llvm::Module(mname); | |
64 | |
6 | 65 // set target stuff |
1 | 66 std::string target_triple(global.params.tt_arch); |
67 target_triple.append(global.params.tt_os); | |
68 ir.module->setTargetTriple(target_triple); | |
69 ir.module->setDataLayout(global.params.data_layout); | |
70 | |
71 gTargetData = new llvm::TargetData(ir.module); | |
72 | |
6 | 73 // process module members |
1 | 74 for (int k=0; k < members->dim; k++) { |
75 Dsymbol* dsym = (Dsymbol*)(members->data[k]); | |
76 assert(dsym); | |
77 dsym->toObjFile(); | |
78 } | |
79 | |
80 delete gTargetData; | |
81 gTargetData = 0; | |
82 | |
6 | 83 // verify the llvm |
1 | 84 std::string verifyErr; |
85 if (llvm::verifyModule(*ir.module,llvm::ReturnStatusAction,&verifyErr)) | |
86 { | |
87 error("%s", verifyErr.c_str()); | |
88 fatal(); | |
89 } | |
90 | |
6 | 91 // emit the llvm main function if necessary |
1 | 92 if (ir.emitMain) { |
93 LLVM_DtoMain(); | |
94 } | |
95 | |
96 // run passes | |
97 // TODO | |
98 | |
99 /*if (global.params.llvmLL) { | |
100 //assert(0); | |
101 std::ofstream os(llfile->name->toChars()); | |
102 //llvm::WriteAssemblyToFile(ir.module, os); | |
103 ir.module->print(os); | |
104 }*/ | |
105 | |
6 | 106 // write bytecode |
1 | 107 //if (global.params.llvmBC) { |
108 Logger::println("Writing LLVM bitcode\n"); | |
109 std::ofstream os(bcfile->name->toChars(), std::ios::binary); | |
110 llvm::WriteBitcodeToFile(ir.module, os); | |
111 //} | |
112 | |
113 delete ir.module; | |
114 gIR = NULL; | |
115 } | |
116 | |
117 /* ================================================================== */ | |
118 | |
119 // Put out instance of ModuleInfo for this Module | |
120 | |
121 void Module::genmoduleinfo() | |
122 { | |
123 } | |
124 | |
125 /* ================================================================== */ | |
126 | |
127 void Dsymbol::toObjFile() | |
128 { | |
129 warning("Ignoring Dsymbol::toObjFile for %s", toChars()); | |
130 } | |
131 | |
132 /* ================================================================== */ | |
133 | |
134 void Declaration::toObjFile() | |
135 { | |
136 warning("Ignoring Declaration::toObjFile for %s", toChars()); | |
137 } | |
138 | |
139 /* ================================================================== */ | |
140 | |
6 | 141 /// Returns the LLVM style index from a DMD style offset |
8
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
142 void AggregateDeclaration::offsetToIndex(unsigned os, std::vector<unsigned>& result) |
1 | 143 { |
8
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
144 unsigned vos = 0; |
1 | 145 for (unsigned i=0; i<fields.dim; ++i) { |
146 VarDeclaration* vd = (VarDeclaration*)fields.data[i]; | |
8
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
147 if (vd->type->ty == Tstruct) { |
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
148 if (vos + vd->type->size() > os) { |
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
149 TypeStruct* ts = (TypeStruct*)vd->type; |
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
150 StructDeclaration* sd = ts->sym; |
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
151 result.push_back(i); |
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
152 sd->offsetToIndex(os - vos, result); |
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
153 return; |
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
154 } |
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
155 } |
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
156 else if (os == vd->offset) { |
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
157 result.push_back(i); |
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
158 return; |
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
159 } |
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
160 vos += vd->offset; |
1 | 161 } |
162 assert(0 && "Offset not found in any aggregate field"); | |
163 } | |
164 | |
165 /* ================================================================== */ | |
166 | |
167 static unsigned LLVM_ClassOffsetToIndex(ClassDeclaration* cd, unsigned os, unsigned& idx) | |
168 { | |
169 // start at the bottom of the inheritance chain | |
170 if (cd->baseClass != 0) { | |
171 unsigned o = LLVM_ClassOffsetToIndex(cd->baseClass, os, idx); | |
172 if (o != (unsigned)-1) | |
173 return o; | |
174 } | |
175 | |
176 // check this class | |
177 unsigned i; | |
178 for (i=0; i<cd->fields.dim; ++i) { | |
179 VarDeclaration* vd = (VarDeclaration*)cd->fields.data[i]; | |
180 if (os == vd->offset) | |
181 return i+idx; | |
182 } | |
183 idx += i; | |
184 | |
185 return (unsigned)-1; | |
186 } | |
187 | |
6 | 188 /// Returns the LLVM style index from a DMD style offset |
189 /// Handles class inheritance | |
8
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
190 void ClassDeclaration::offsetToIndex(unsigned os, std::vector<unsigned>& result) |
1 | 191 { |
192 unsigned idx = 0; | |
193 unsigned r = LLVM_ClassOffsetToIndex(this, os, idx); | |
194 assert(r != (unsigned)-1 && "Offset not found in any aggregate field"); | |
8
5e69b77a5c51
[svn r12] fixed accessing aggregate fields of aggregates
lindquist
parents:
6
diff
changeset
|
195 result.push_back(r+1); // vtable is 0 |
1 | 196 } |
197 | |
198 /* ================================================================== */ | |
199 | |
200 void InterfaceDeclaration::toObjFile() | |
201 { | |
202 warning("Ignoring InterfaceDeclaration::toObjFile for %s", toChars()); | |
203 } | |
204 | |
205 /* ================================================================== */ | |
206 | |
207 void StructDeclaration::toObjFile() | |
208 { | |
209 TypeStruct* ts = (TypeStruct*)type; | |
210 if (llvmType != 0) | |
211 return; | |
212 | |
213 static int sdi = 0; | |
214 Logger::print("StructDeclaration::toObjFile(%d): %s\n", sdi++, toChars()); | |
215 LOG_SCOPE; | |
216 | |
217 gIR->structs.push_back(IRStruct(ts)); | |
218 | |
219 std::vector<FuncDeclaration*> mfs; | |
220 | |
221 for (int k=0; k < members->dim; k++) { | |
222 Dsymbol* dsym = (Dsymbol*)(members->data[k]); | |
223 | |
224 // need late generation of member functions | |
225 // they need the llvm::StructType to exist to take the 'this' parameter | |
226 if (FuncDeclaration* fd = dsym->isFuncDeclaration()) { | |
227 mfs.push_back(fd); | |
228 } | |
229 else { | |
230 dsym->toObjFile(); | |
231 } | |
232 } | |
233 | |
234 llvm::StructType* structtype = llvm::StructType::get(gIR->topstruct().fields); | |
235 | |
236 // refine abstract types for stuff like: struct S{S* next;} | |
237 if (gIR->topstruct().recty != 0) | |
238 { | |
239 llvm::PATypeHolder& pa = gIR->topstruct().recty; | |
240 llvm::cast<llvm::OpaqueType>(pa.get())->refineAbstractTypeTo(structtype); | |
241 structtype = llvm::cast<llvm::StructType>(pa.get()); | |
242 } | |
243 | |
244 ts->llvmType = structtype; | |
245 llvmType = structtype; | |
246 | |
247 if (parent->isModule()) { | |
248 gIR->module->addTypeName(mangle(),ts->llvmType); | |
249 } | |
250 | |
251 // generate static data | |
252 llvm::GlobalValue::LinkageTypes _linkage = llvm::GlobalValue::ExternalLinkage; | |
253 llvm::Constant* _init = 0; | |
254 | |
255 // always generate the constant initalizer | |
256 if (!zeroInit) { | |
257 Logger::println("Not zero initialized"); | |
258 //assert(tk == gIR->topstruct().size()); | |
259 #ifndef LLVMD_NO_LOGGER | |
260 Logger::cout() << *structtype << '\n'; | |
261 for (size_t k=0; k<gIR->topstruct().inits.size(); ++k) { | |
262 Logger::cout() << "Type:" << '\n'; | |
263 Logger::cout() << *gIR->topstruct().inits[k]->getType() << '\n'; | |
264 Logger::cout() << "Value:" << '\n'; | |
265 Logger::cout() << *gIR->topstruct().inits[k] << '\n'; | |
266 } | |
267 Logger::cout() << "Initializer printed" << '\n'; | |
268 #endif | |
269 llvmInitZ = llvm::ConstantStruct::get(structtype,gIR->topstruct().inits); | |
270 } | |
271 else { | |
272 Logger::println("Zero initialized"); | |
273 llvmInitZ = llvm::ConstantAggregateZero::get(structtype); | |
274 } | |
275 | |
276 // only provide the constant initializer for the defining module | |
277 if (getModule() == gIR->dmodule) | |
278 { | |
279 _init = llvmInitZ; | |
280 } | |
281 | |
282 std::string initname(mangle()); | |
283 initname.append("__initZ"); | |
284 llvm::GlobalVariable* initvar = new llvm::GlobalVariable(ts->llvmType, true, _linkage, _init, initname, gIR->module); | |
285 ts->llvmInit = initvar; | |
286 | |
287 // generate member functions | |
288 size_t n = mfs.size(); | |
289 for (size_t i=0; i<n; ++i) { | |
290 mfs[i]->toObjFile(); | |
291 } | |
292 | |
293 llvmDModule = gIR->dmodule; | |
294 | |
295 gIR->structs.pop_back(); | |
296 | |
297 // generate typeinfo | |
298 type->getTypeInfo(NULL); // generate TypeInfo | |
299 } | |
300 | |
301 /* ================================================================== */ | |
302 | |
303 static void LLVM_AddBaseClassData(BaseClasses* bcs) | |
304 { | |
305 // add base class data members first | |
306 for (int j=0; j<bcs->dim; j++) | |
307 { | |
308 BaseClass* bc = (BaseClass*)(bcs->data[j]); | |
309 assert(bc); | |
310 LLVM_AddBaseClassData(&bc->base->baseclasses); | |
311 for (int k=0; k < bc->base->members->dim; k++) { | |
312 Dsymbol* dsym = (Dsymbol*)(bc->base->members->data[k]); | |
313 if (dsym->isVarDeclaration()) | |
314 { | |
315 dsym->toObjFile(); | |
316 } | |
317 } | |
318 } | |
319 } | |
320 | |
321 void ClassDeclaration::toObjFile() | |
322 { | |
323 TypeClass* ts = (TypeClass*)type; | |
324 if (ts->llvmType != 0 || llvmInProgress) | |
325 return; | |
326 | |
327 llvmInProgress = true; | |
328 | |
329 static int fdi = 0; | |
330 Logger::print("ClassDeclaration::toObjFile(%d): %s\n", fdi++, toChars()); | |
331 LOG_SCOPE; | |
332 | |
6 | 333 gIR->structs.push_back(IRStruct(ts)); |
1 | 334 gIR->classes.push_back(this); |
335 gIR->classmethods.push_back(IRState::FuncDeclVec()); | |
336 gIR->queueClassMethods.push_back(true); | |
337 | |
338 // add vtable | |
339 const llvm::Type* vtabty = llvm::PointerType::get(llvm::Type::Int8Ty); | |
340 gIR->topstruct().fields.push_back(vtabty); | |
341 gIR->topstruct().inits.push_back(0); | |
342 | |
343 // base classes first | |
344 LLVM_AddBaseClassData(&baseclasses); | |
345 | |
346 // then add own members | |
347 for (int k=0; k < members->dim; k++) { | |
348 Dsymbol* dsym = (Dsymbol*)(members->data[k]); | |
349 dsym->toObjFile(); | |
350 } | |
351 | |
352 llvm::StructType* structtype = llvm::StructType::get(gIR->topstruct().fields); | |
6 | 353 // refine abstract types for stuff like: class C {C next;} |
354 if (gIR->topstruct().recty != 0) | |
355 { | |
356 llvm::PATypeHolder& pa = gIR->topstruct().recty; | |
357 llvm::cast<llvm::OpaqueType>(pa.get())->refineAbstractTypeTo(structtype); | |
358 structtype = llvm::cast<llvm::StructType>(pa.get()); | |
359 } | |
360 | |
1 | 361 ts->llvmType = structtype; |
362 llvmType = structtype; | |
363 | |
364 bool emit_vtable = false; | |
365 bool define_vtable = false; | |
366 if (parent->isModule()) { | |
367 gIR->module->addTypeName(mangle(),ts->llvmType); | |
368 emit_vtable = true; | |
369 define_vtable = (getModule() == gIR->dmodule); | |
370 } | |
371 else { | |
372 assert(0 && "class parent is not a module"); | |
373 } | |
374 | |
375 // generate member functions | |
376 gIR->queueClassMethods.back() = false; | |
377 IRState::FuncDeclVec& mfs = gIR->classmethods.back(); | |
378 size_t n = mfs.size(); | |
379 for (size_t i=0; i<n; ++i) { | |
380 mfs[i]->toObjFile(); | |
381 } | |
382 | |
383 // create vtable initializer | |
384 if (emit_vtable) | |
385 { | |
386 llvm::GlobalVariable* vtblVar = 0; | |
387 std::vector<llvm::Constant*> inits; | |
388 inits.reserve(vtbl.dim); | |
389 for (int k=0; k < vtbl.dim; k++) | |
390 { | |
391 Dsymbol* dsym = (Dsymbol*)vtbl.data[k]; | |
392 assert(dsym); | |
393 //Logger::cout() << "vtblsym: " << dsym->toChars() << '\n'; | |
394 | |
395 if (FuncDeclaration* fd = dsym->isFuncDeclaration()) { | |
396 fd->toObjFile(); | |
397 Logger::cout() << "casting to constant" << *fd->llvmValue << '\n'; | |
398 llvm::Constant* c = llvm::cast<llvm::Constant>(fd->llvmValue); | |
399 c = llvm::ConstantExpr::getBitCast(c, llvm::PointerType::get(llvm::Type::Int8Ty)); | |
400 inits.push_back(c); | |
401 } | |
402 else if (ClassDeclaration* cd = dsym->isClassDeclaration()) { | |
403 llvm::Constant* c = llvm::Constant::getNullValue(llvm::PointerType::get(llvm::Type::Int8Ty)); | |
404 inits.push_back(c); | |
405 } | |
406 else | |
407 assert(0); | |
408 } | |
409 if (!inits.empty()) | |
410 { | |
411 llvm::GlobalValue::LinkageTypes _linkage = llvm::GlobalValue::ExternalLinkage; | |
412 std::string varname(mangle()); | |
413 varname.append("__vtblZ"); | |
414 const llvm::ArrayType* vtbl_ty = llvm::ArrayType::get(llvm::PointerType::get(llvm::Type::Int8Ty), inits.size()); | |
415 vtblVar = new llvm::GlobalVariable(vtbl_ty, true, _linkage, 0, varname, gIR->module); | |
416 if (define_vtable) { | |
417 //Logger::cout() << "vtbl:::" << '\n' << *vtbl_st << '\n';// << " == | == " << _init << '\n'; | |
418 llvm::Constant* _init = llvm::ConstantArray::get(vtbl_ty, inits); | |
419 vtblVar->setInitializer(_init); | |
420 } | |
421 llvmVtbl = vtblVar; | |
422 } | |
423 | |
424 //////////////////////////////////////////////////////////////////////////////// | |
425 | |
426 // generate initializer | |
427 llvm::GlobalValue::LinkageTypes _linkage = llvm::GlobalValue::ExternalLinkage; | |
428 llvm::Constant* _init = 0; | |
429 | |
430 // first field is always the vtable | |
431 assert(vtblVar != 0); | |
432 llvm::Constant* vtbl_init_var = llvm::ConstantExpr::getBitCast(vtblVar, llvm::PointerType::get(llvm::Type::Int8Ty)); | |
433 gIR->topstruct().inits[0] = vtbl_init_var; | |
434 | |
435 //assert(tk == gIR->topstruct().size()); | |
436 #ifndef LLVMD_NO_LOGGER | |
437 Logger::cout() << *structtype << '\n'; | |
438 for (size_t k=0; k<gIR->topstruct().inits.size(); ++k) | |
439 Logger::cout() << *gIR->topstruct().inits[k] << '\n'; | |
440 #endif | |
441 _init = llvm::ConstantStruct::get(structtype,gIR->topstruct().inits); | |
442 assert(_init); | |
443 std::string initname(mangle()); | |
444 initname.append("__initZ"); | |
445 Logger::cout() << *_init << '\n'; | |
446 llvm::GlobalVariable* initvar = new llvm::GlobalVariable(ts->llvmType, true, _linkage, 0, initname, gIR->module); | |
447 ts->llvmInit = initvar; | |
448 if (define_vtable) { | |
449 initvar->setInitializer(_init); | |
450 } | |
451 } | |
452 | |
453 gIR->queueClassMethods.pop_back(); | |
454 gIR->classmethods.pop_back(); | |
455 gIR->classes.pop_back(); | |
456 gIR->structs.pop_back(); | |
457 | |
458 llvmInProgress = false; | |
459 } | |
460 | |
461 /****************************************** | |
462 * Get offset of base class's vtbl[] initializer from start of csym. | |
463 * Returns ~0 if not this csym. | |
464 */ | |
465 | |
466 unsigned ClassDeclaration::baseVtblOffset(BaseClass *bc) | |
467 { | |
468 return ~0; | |
469 } | |
470 | |
471 /* ================================================================== */ | |
472 | |
473 void VarDeclaration::toObjFile() | |
474 { | |
475 static int vdi = 0; | |
476 Logger::print("VarDeclaration::toObjFile(%d): %s | %s\n", vdi++, toChars(), type->toChars()); | |
477 LOG_SCOPE; | |
478 llvm::Module* M = gIR->module; | |
479 | |
480 // handle bind pragma | |
481 if (llvmInternal == LLVMbind) { | |
482 Logger::println("var is bound: %s", llvmInternal1); | |
483 llvmValue = M->getGlobalVariable(llvmInternal1); | |
484 assert(llvmValue); | |
485 return; | |
486 } | |
487 | |
488 // global variable or magic | |
489 if (!parent || parent->isModule()) | |
490 { | |
491 bool _isconst = isConst(); | |
492 if (!_isconst) | |
493 _isconst = (storage_class & STCconst) ? true : false; // doesn't seem to work ): | |
494 llvm::GlobalValue::LinkageTypes _linkage = LLVM_DtoLinkage(protection, storage_class); | |
495 const llvm::Type* _type = LLVM_DtoType(type); | |
496 | |
497 llvm::Constant* _init = 0; | |
498 bool _signed = !type->isunsigned(); | |
499 | |
500 _init = LLVM_DtoInitializer(type, init); | |
501 | |
502 assert(_type); | |
503 assert(_init); | |
504 //Logger::cout() << "initializer: " << *_init << '\n'; | |
505 if (_type != _init->getType()) { | |
506 Logger::cout() << "got type '" << *_init->getType() << "' expected '" << *_type << "'\n"; | |
507 // zero initalizer | |
508 if (_init->isNullValue()) | |
509 _init = llvm::Constant::getNullValue(_type); | |
510 // pointer to global constant (struct.init) | |
511 else if (llvm::isa<llvm::GlobalVariable>(_init)) | |
512 { | |
513 assert(_init->getType()->getContainedType(0) == _type); | |
514 llvm::GlobalVariable* gv = llvm::cast<llvm::GlobalVariable>(_init); | |
515 assert(type->ty == Tstruct); | |
516 TypeStruct* ts = (TypeStruct*)type; | |
517 assert(ts->sym->llvmInitZ); | |
518 _init = ts->sym->llvmInitZ; | |
519 } | |
520 // array single value init | |
521 else if (llvm::isa<llvm::ArrayType>(_type)) | |
522 { | |
523 const llvm::ArrayType* at = llvm::cast<llvm::ArrayType>(_type); | |
524 assert(_type->getContainedType(0) == _init->getType()); | |
525 std::vector<llvm::Constant*> initvals; | |
526 initvals.resize(at->getNumElements(), _init); | |
527 _init = llvm::ConstantArray::get(at, initvals); | |
528 } | |
529 else | |
530 assert(0); | |
531 } | |
532 | |
533 Logger::println("Creating global variable"); | |
534 std::string _name(mangle()); | |
535 llvm::GlobalVariable* gvar = new llvm::GlobalVariable(_type,_isconst,_linkage,_init,_name,M); | |
536 llvmValue = gvar; | |
537 | |
538 //if (storage_class & STCprivate) | |
539 // gvar->setVisibility(llvm::GlobalValue::ProtectedVisibility); | |
540 } | |
541 | |
542 // inside aggregate declaration. declare a field. | |
543 else | |
544 { | |
545 Logger::println("Aggregate var declaration: '%s' offset=%d", toChars(), offset); | |
546 | |
547 const llvm::Type* _type = LLVM_DtoType(type); | |
548 gIR->topstruct().fields.push_back(_type); | |
549 | |
550 llvm::Constant* _init = LLVM_DtoInitializer(type, init); | |
551 if (_type != _init->getType()) | |
552 { | |
553 if (llvm::isa<llvm::ArrayType>(_type)) | |
554 { | |
555 const llvm::ArrayType* arrty = llvm::cast<llvm::ArrayType>(_type); | |
556 uint64_t n = arrty->getNumElements(); | |
557 std::vector<llvm::Constant*> vals(n,_init); | |
558 _init = llvm::ConstantArray::get(arrty, vals); | |
559 } | |
6 | 560 else if (llvm::isa<llvm::StructType>(_type)) { |
561 const llvm::StructType* structty = llvm::cast<llvm::StructType>(_type); | |
562 TypeStruct* ts = (TypeStruct*)type; | |
563 assert(ts->sym->llvmInitZ); | |
564 _init = ts->sym->llvmInitZ; | |
565 } | |
1 | 566 else |
567 assert(0); | |
568 } | |
569 gIR->topstruct().inits.push_back(_init); | |
570 } | |
571 | |
572 Logger::println("VarDeclaration::toObjFile is done"); | |
573 } | |
574 | |
575 /* ================================================================== */ | |
576 | |
577 void TypedefDeclaration::toObjFile() | |
578 { | |
579 static int tdi = 0; | |
580 Logger::print("TypedefDeclaration::toObjFile(%d): %s\n", tdi++, toChars()); | |
581 LOG_SCOPE; | |
582 | |
583 // TODO | |
584 } | |
585 | |
586 /* ================================================================== */ | |
587 | |
588 void EnumDeclaration::toObjFile() | |
589 { | |
590 warning("Ignoring EnumDeclaration::toObjFile for %s", toChars()); | |
591 } | |
592 | |
593 /* ================================================================== */ | |
594 | |
595 void FuncDeclaration::toObjFile() | |
596 { | |
597 if (llvmValue != 0 && llvmDModule == gIR->dmodule) { | |
598 return; | |
599 } | |
600 | |
601 // has already been pulled in by a reference to ( | |
602 if (!gIR->queueClassMethods.empty() && gIR->queueClassMethods.back()) { | |
603 Logger::println("queueing %s", toChars()); | |
604 assert(!gIR->classmethods.empty()); | |
605 gIR->classmethods.back().push_back(this); | |
606 return; // will be generated later when the this parameter has a type | |
607 } | |
608 | |
609 static int fdi = 0; | |
610 Logger::print("FuncDeclaration::toObjFile(%d,%s): %s\n", fdi++, needThis()?"this":"static",toChars()); | |
611 LOG_SCOPE; | |
612 | |
613 if (llvmInternal == LLVMintrinsic && fbody) { | |
614 error("intrinsics cannot have function bodies"); | |
615 fatal(); | |
616 } | |
617 | |
618 TypeFunction* f = (TypeFunction*)type; | |
619 assert(f != 0); | |
620 | |
621 // return value type | |
622 const llvm::Type* rettype; | |
623 const llvm::Type* actualRettype; | |
624 Type* rt = f->next; | |
625 bool retinptr = false; | |
626 bool usesthis = false; | |
627 | |
628 if (isMain()) { | |
629 rettype = llvm::Type::Int32Ty; | |
630 actualRettype = rettype; | |
631 gIR->emitMain = true; | |
632 } | |
633 else if (rt) { | |
634 if (rt->ty == Tstruct || rt->ty == Tdelegate || rt->ty == Tarray) { | |
635 rettype = llvm::PointerType::get(LLVM_DtoType(rt)); | |
636 actualRettype = llvm::Type::VoidTy; | |
637 f->llvmRetInPtr = retinptr = true; | |
638 } | |
639 else { | |
640 rettype = LLVM_DtoType(rt); | |
641 actualRettype = rettype; | |
642 } | |
643 } | |
644 else { | |
645 assert(0); | |
646 } | |
647 | |
648 // parameter types | |
649 std::vector<const llvm::Type*> paramvec; | |
650 | |
651 if (retinptr) { | |
652 Logger::print("returning through pointer parameter\n"); | |
653 paramvec.push_back(rettype); | |
654 } | |
655 | |
656 if (needThis()) { | |
657 if (AggregateDeclaration* ad = isMember()) { | |
658 Logger::print("isMember = this is: %s\n", ad->type->toChars()); | |
659 const llvm::Type* thisty = LLVM_DtoType(ad->type); | |
660 if (llvm::isa<llvm::StructType>(thisty)) | |
661 thisty = llvm::PointerType::get(thisty); | |
662 paramvec.push_back(thisty); | |
663 usesthis = true; | |
664 } | |
665 else | |
666 assert(0); | |
667 } | |
668 | |
669 size_t n = Argument::dim(f->parameters); | |
670 for (int i=0; i < n; ++i) { | |
671 Argument* arg = Argument::getNth(f->parameters, i); | |
672 // ensure scalar | |
673 Type* argT = arg->type; | |
674 assert(argT); | |
675 | |
676 if ((arg->storageClass & STCref) || (arg->storageClass & STCout)) { | |
677 //assert(arg->vardecl); | |
678 //arg->vardecl->refparam = true; | |
679 } | |
680 else | |
681 arg->llvmCopy = true; | |
682 | |
683 const llvm::Type* at = LLVM_DtoType(argT); | |
684 if (llvm::isa<llvm::StructType>(at)) { | |
685 Logger::println("struct param"); | |
686 paramvec.push_back(llvm::PointerType::get(at)); | |
687 } | |
688 else if (llvm::isa<llvm::ArrayType>(at)) { | |
689 Logger::println("sarray param"); | |
690 assert(argT->ty == Tsarray); | |
691 //paramvec.push_back(llvm::PointerType::get(at->getContainedType(0))); | |
692 paramvec.push_back(llvm::PointerType::get(at)); | |
693 } | |
694 else { | |
695 if (!arg->llvmCopy) { | |
696 Logger::println("ref param"); | |
697 at = llvm::PointerType::get(at); | |
698 } | |
699 else { | |
700 Logger::println("in param"); | |
701 } | |
702 paramvec.push_back(at); | |
703 } | |
704 } | |
705 | |
706 // construct function | |
707 bool isvararg = f->varargs; | |
708 llvm::FunctionType* functype = llvm::FunctionType::get(actualRettype, paramvec, isvararg); | |
709 | |
710 // mangled name | |
711 char* mangled_name = (llvmInternal == LLVMintrinsic) ? llvmInternal1 : mangle(); | |
712 llvm::Function* func = gIR->module->getFunction(mangled_name); | |
713 | |
714 // make the function | |
715 /*if (func != 0) { | |
716 llvmValue = func; | |
717 f->llvmType = functype; | |
718 return; // already pulled in from a forward declaration | |
719 } | |
720 else */ | |
721 if (func == 0) { | |
722 func = new llvm::Function(functype,LLVM_DtoLinkage(protection, storage_class),mangled_name,gIR->module); | |
723 } | |
724 | |
725 if (llvmInternal != LLVMintrinsic) | |
726 func->setCallingConv(LLVM_DtoCallingConv(f->linkage)); | |
727 | |
728 llvmValue = func; | |
729 f->llvmType = functype; | |
730 | |
731 if (isMain()) { | |
732 gIR->mainFunc = func; | |
733 } | |
734 | |
735 // name parameters | |
736 llvm::Function::arg_iterator iarg = func->arg_begin(); | |
737 int k = 0; | |
738 int nunnamed = 0; | |
739 if (retinptr) { | |
740 iarg->setName("retval"); | |
741 f->llvmRetArg = iarg; | |
742 ++iarg; | |
743 } | |
744 if (usesthis) { | |
745 iarg->setName("this"); | |
746 ++iarg; | |
747 } | |
748 for (; iarg != func->arg_end(); ++iarg) | |
749 { | |
750 Argument* arg = Argument::getNth(f->parameters, k++); | |
751 //arg->llvmValue = iarg; | |
752 //printf("identifier: '%s' %p\n", arg->ident->toChars(), arg->ident); | |
753 if (arg->ident != 0) { | |
754 if (arg->vardecl) { | |
755 arg->vardecl->llvmValue = iarg; | |
756 } | |
757 iarg->setName(arg->ident->toChars()); | |
758 } | |
759 else { | |
760 ++nunnamed; | |
761 } | |
762 } | |
763 | |
764 // only members of the current module maybe be defined | |
765 if (getModule() == gIR->dmodule) | |
766 { | |
767 bool allow_fbody = true; | |
768 // handle static constructor / destructor | |
769 if (isStaticCtorDeclaration() || isStaticDtorDeclaration()) { | |
770 const llvm::ArrayType* sctor_type = llvm::ArrayType::get(llvm::PointerType::get(functype),1); | |
771 //Logger::cout() << "static ctor type: " << *sctor_type << '\n'; | |
772 | |
773 llvm::Constant* sctor_func = llvm::cast<llvm::Constant>(llvmValue); | |
774 //Logger::cout() << "static ctor func: " << *sctor_func << '\n'; | |
775 | |
776 llvm::Constant* sctor_init = 0; | |
777 if (llvmInternal == LLVMnull) | |
778 { | |
779 llvm::Constant* sctor_init_null = llvm::Constant::getNullValue(sctor_func->getType()); | |
780 sctor_init = llvm::ConstantArray::get(sctor_type,&sctor_init_null,1); | |
781 allow_fbody = false; | |
782 } | |
783 else | |
784 { | |
785 sctor_init = llvm::ConstantArray::get(sctor_type,&sctor_func,1); | |
786 } | |
787 | |
788 //Logger::cout() << "static ctor init: " << *sctor_init << '\n'; | |
789 | |
790 | |
791 // output the llvm.global_ctors array | |
792 const char* varname = isStaticCtorDeclaration() ? "_d_module_ctor_array" : "_d_module_dtor_array"; | |
793 llvm::GlobalVariable* sctor_arr = new llvm::GlobalVariable(sctor_type, false, llvm::GlobalValue::AppendingLinkage, sctor_init, varname, gIR->module); | |
794 } | |
795 | |
796 // function definition | |
797 if (allow_fbody && fbody != 0) | |
798 { | |
799 assert(nunnamed == 0); | |
800 gIR->funcs.push(func); | |
801 gIR->functypes.push(f); | |
802 | |
803 IRScope irs; | |
804 irs.begin = new llvm::BasicBlock("entry",func); | |
805 irs.end = new llvm::BasicBlock("endentry",func); | |
806 | |
807 //assert(gIR->scopes.empty()); | |
808 gIR->scopes.push_back(irs); | |
809 | |
810 // create alloca point | |
811 f->llvmAllocaPoint = new llvm::BitCastInst(llvm::ConstantInt::get(llvm::Type::Int32Ty,0,false),llvm::Type::Int32Ty,"alloca point",gIR->scopebb()); | |
812 | |
813 // output function body | |
814 fbody->toIR(gIR); | |
815 | |
816 // llvm requires all basic blocks to end with a TerminatorInst but DMD does not put a return statement | |
817 // in automatically, so we do it here. | |
818 if (!isMain() && (gIR->scopebb()->empty() || !llvm::isa<llvm::TerminatorInst>(gIR->scopebb()->back()))) { | |
819 // pass the previous block into this block | |
820 //new llvm::BranchInst(irs.end, irs.begin); | |
821 new llvm::ReturnInst(gIR->scopebb()); | |
822 } | |
823 | |
824 // erase alloca point | |
825 f->llvmAllocaPoint->eraseFromParent(); | |
826 f->llvmAllocaPoint = 0; | |
827 | |
828 gIR->scopes.pop_back(); | |
829 //assert(gIR->scopes.empty()); | |
830 | |
831 gIR->functypes.pop(); | |
832 gIR->funcs.pop(); | |
833 | |
834 // get rid of the endentry block, it's never used | |
835 func->getBasicBlockList().pop_back(); | |
836 | |
837 // if the last block is empty now, it must be unreachable or it's a bug somewhere else | |
838 llvm::BasicBlock* lastbb = &func->getBasicBlockList().back(); | |
839 if (lastbb->empty()) { | |
840 new llvm::UnreachableInst(lastbb); | |
841 } | |
842 } | |
843 } | |
844 else | |
845 { | |
846 Logger::println("only declaration"); | |
847 } | |
848 | |
849 llvmDModule = gIR->dmodule; | |
850 | |
851 Logger::println("FuncDeclaration done\n"); | |
852 } |