summaryrefslogtreecommitdiff
path: root/MLKLLVMCompiler.mm
blob: 72b455b169c99a36cc58c869a2c1777b4b1913ed (plain)
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
/* -*- mode: objc; coding: utf-8 -*- */
/* Toilet Lisp, a Common Lisp subset for the Étoilé runtime.
 * Copyright (C) 2008  Matthias Andreas Benkard.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#import "MLKCompiledClosure.h"
#import "MLKDynamicContext.h"
#import "MLKLexicalContext-MLKLLVMCompilation.h"
#import "MLKLLVMCompiler.h"
#import "MLKPackage.h"
#import "globals.h"
#import "llvm_context.h"
#import "util.h"

#import <Foundation/NSArray.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSEnumerator.h>
#import <Foundation/NSString.h>

#ifdef __OBJC_GC__
#import <Foundation/NSGarbageCollector.h>
#endif


#include <llvm/Analysis/Verifier.h>
#include <llvm/BasicBlock.h>
#include <llvm/CallingConv.h>
#include <llvm/DerivedTypes.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/Instructions.h>
//#include <llvm/Interpreter.h>
#include <llvm/Module.h>
#include <llvm/PassManager.h>
#include <llvm/Support/IRBuilder.h>
#include <llvm/Target/TargetData.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/Utils/Cloning.h>  // InlineFunction
#include <llvm/Transforms/Utils/UnifyFunctionExitNodes.h>
#include <llvm/Value.h>

#include <deque>
#include <vector>

#include <stddef.h>
#ifdef MACOSX
#include <objc/objc-api.h>
#if defined(OBJC_API_VERSION) && OBJC_API_VERSION >= 2
#include <objc/runtime.h>
#endif
#endif

using namespace llvm;
using namespace std;


static ExecutionEngine *execution_engine;
static llvm::Module *module;
static IRBuilder<true, ConstantFolder> builder(llvm_context);
static FunctionPassManager *fpm;


static Constant
*createGlobalStringPtr (const char *string)
{
  Constant *(indices[2]);
  indices[0] = indices[1] = ConstantInt::get (Int32Ty, 0);

  Constant *str = ConstantArray::get (llvm_context, string);
  Constant *str2 = new GlobalVariable (str->getType(),
                                       true, 
                                       GlobalValue::InternalLinkage,
                                       str,
                                       "",
                                       module);
  Constant *ptr = ConstantExpr::getGetElementPtr (str2, indices, 2);
  return ptr;
}


@implementation MLKLLVMCompiler
+(void) load
{
  if (!MLKDefaultCompiler)
    {
      MLKDefaultCompiler = self;
      MLKLoadCompilesP = YES;
    }

  // GNU ld optimises the MLKLLVMCompilation category on
  // MLKLexicalContext away unless we do this.  Man, the crappiness of
  // this Unix stuff is amazing...
  MLKDummyUseLLVMLexicalContext = nil;
}

+(void) initialize
{
  module = new llvm::Module ("MLKLLVMModule", llvm_context);

  //execution_engine = ExecutionEngine::create (module, true);
  execution_engine = ExecutionEngine::create (module, false);

  fpm = new FunctionPassManager (module);
  fpm->add (new TargetData (*execution_engine->getTargetData()));
  //fpm->add (new TargetData (module));
  fpm->add (createScalarReplAggregatesPass());
  fpm->add (createInstructionCombiningPass());
  fpm->add (createReassociatePass());
  fpm->add (createGVNPass());
  //  fpm->add (createVerifierPass());
  //fpm->add (createLowerSetJmpPass());
  //fpm->add (createRaiseAllocationsPass());
  fpm->add (createCFGSimplificationPass());
  fpm->add (createPromoteMemoryToRegisterPass());
  //fpm->add (createGlobalOptimizerPass());
  //fpm->add (createGlobalDCEPass());
  //fpm->add (createFunctionInliningPass());

  // Utilities.
  //  fpm->add (createUnifyFunctionExitNodesPass());
}

+(id) compile:(id)object
    inContext:(MLKLexicalContext *)context
{
  NSAutoreleasePool *pool;
  pool = [[NSAutoreleasePool alloc] init];

  Value *v = NULL;
  BasicBlock *block;
  vector<const Type*> noargs (0, VoidTy);
  FunctionType *function_type = FunctionType::get (VoidPointerTy,
                                                   noargs,
                                                   false);
  Function *function = Function::Create (function_type,
                                         Function::ExternalLinkage,
                                         "",
                                         module);
  id lambdaForm;
  //id (*fn)();
  MLKForm *form = [MLKForm formWithObject:object
                           inContext:context
                           forCompiler:self];
  [self markVariablesForHeapAllocationInForm:form];

  block = BasicBlock::Create (llvm_context, "entry", function);
  builder.SetInsertPoint (block);

  v = [self processForm:form];

  builder.CreateRet (v);
  verifyFunction (*function);
  fpm->run (*function);

  //function->dump();

  //module->dump();
  //NSLog (@"%p", fn);

  LRELEASE (pool);
  //NSLog (@"Code compiled.");

#if 1
  // JIT-compile.
  vector<GenericValue> nogenericargs;
  lambdaForm = (id)execution_engine->runFunction (function, nogenericargs).PointerVal;
  //fn = (id (*)()) execution_engine->getPointerToFunction (function);
  // Execute.
  //lambdaForm = fn();
  // FIXME: Free machine code when appropriate.  (I.e. now?  But this crashes after a LOAD.)
  //execution_engine->freeMachineCodeForFunction (function);
#else
  Interpreter *i = Interpreter::create (module);
  lambdaForm = i->runFunction (function)->PointerVal;
#endif

  //NSLog (@"Function: %p / %p", function, execution_engine->getPointerToFunction (function));
  //NSLog (@"Executed: %p", fn);
  //NSLog (@"Closure built: %p", lambdaForm);

  return lambdaForm;
}

+(void) processTopLevelForm:(id)object
{
  [self processTopLevelForm:object
        inMode:not_compile_time_mode];
}


+(void) processTopLevelForm:(id)object
                     inMode:(enum MLKProcessingMode)mode
{
  //FIXME
  // If PROGN, do this...  If EVAL-WHEN, do that...

}

+(id) eval:(id)object
{
  return [self compile:object
               inContext:[MLKLexicalContext globalContext]];
}

+(Value *) processForm:(MLKForm *)form
{
  return [form processForLLVMWithMultiValue:NULL];
}

+(void) markVariablesForHeapAllocationInForm:(MLKForm *)form
{
  NSArray *subforms = [form subforms];
  unsigned int i;

  for (i = 0; i < [subforms count]; i++)
    {
      MLKForm *subform = [subforms objectAtIndex:i];

      [self markVariablesForHeapAllocationInForm:subform];

      if ([subform isKindOfClass:[MLKSimpleLambdaForm class]]
          || [subform isKindOfClass:[MLKLambdaForm class]])
        {
          NSArray *freeVariables = [[subform freeVariables] allObjects];
          unsigned int j;

          for (j = 0; j < [freeVariables count]; j++)
            {
              id variable = [freeVariables objectAtIndex:j];
              [[subform context] setVariableHeapAllocation:YES
                                 forSymbol:variable];
            }
        }
    }
}

+(Value *) insertSelectorLookup:(NSString *)name
{
  Constant *function = 
    module->getOrInsertFunction (
#ifdef __NEXT_RUNTIME__
                                 "sel_getUid",
#else
                                 "sel_get_uid",
#endif
                                 VoidPointerTy,
                                 VoidPointerTy,
                                 NULL);

  Constant *nameptr = createGlobalStringPtr ([name UTF8String]);
  return builder.CreateCall (function, nameptr, "selector");
}

+(Value *) insertMethodCall:(NSString *)messageName
                   onObject:(Value *)object
         withArgumentVector:(vector<Value*> *)argv
{
  return [self insertMethodCall:messageName
               onObject:object
               withArgumentVector:argv
               name:@""];
}

+(Value *) insertVoidMethodCall:(NSString *)messageName
                       onObject:(Value *)object
             withArgumentVector:(vector<Value*> *)argv
{
  return [self insertMethodCall:messageName
               onObject:object
               withArgumentVector:argv
               name:@""
               returnType:(VoidTy)];
}

+(Value *) insertMethodCall:(NSString *)messageName
                   onObject:(Value *)object
         withArgumentVector:(vector<Value*> *)argv
                       name:(NSString *)name
{
  return [self insertMethodCall:messageName
               onObject:object
               withArgumentVector:argv
               name:@""
               returnType:VoidPointerTy];
}

+(Value *) insertMethodCall:(NSString *)messageName
                   onObject:(Value *)object
         withArgumentVector:(vector<Value*> *)argv
                       name:(NSString *)name
                 returnType:(const Type *)returnType
{
  vector <const Type *> argtypes (2, VoidPointerTy);
  FunctionType *ftype = FunctionType::get (returnType, argtypes, true);

  Value *sel = [self insertSelectorLookup:messageName];

#ifdef __NEXT_RUNTIME__
  Constant *function = 
    module->getOrInsertFunction ("objc_msgSend", ftype);
#else
  vector <const Type *> lookup_argtypes (2, VoidPointerTy);
  FunctionType *lookup_ftype = FunctionType::get (PointerType::get (ftype, 0),
                                                  lookup_argtypes,
                                                  false);
  Constant *lookup_function = 
    module->getOrInsertFunction ("objc_msg_lookup", lookup_ftype);
  Value *function =
    builder.CreateCall2 (lookup_function, object, sel, "method_impl");
#endif

  // XXX The following doesn't work.  Why?
  //  deque <Value *> argd (*argv);
  //  argd.push_front (sel);
  //  argd.push_front (object);

  vector <Value *> argd;
  argd.push_back (object);
  argd.push_back (sel);
  vector<Value *>::iterator e;
  for (e = argv->begin(); e != argv->end(); e++)
    argd.push_back (*e);

  return builder.CreateCall (function, argd.begin(), argd.end());
}

+(Value *) insertMethodCall:(NSString *)messageName
                   onObject:(Value *)object
                   withName:(NSString *)name
{
  vector<Value*> argv;
  return [self insertMethodCall:messageName
               onObject:object
               withArgumentVector:&argv
               name:name];
}

+(Value *) insertMethodCall:(NSString *)messageName
                   onObject:(Value *)object
{
  return [self insertMethodCall:messageName
               onObject:object
               withName:@""];
}

+(Value *) insertClassLookup:(NSString *)className
{
  Constant *function = 
    module->getOrInsertFunction (
#ifdef __NEXT_RUNTIME__
                                 "objc_getClass",
#else
                                 "objc_get_class",
#endif
                                 VoidPointerTy,
                                 VoidPointerTy,
                                 NULL);

  const char *cname = [className UTF8String];

  // Value *nameptr = builder.CreateGlobalStringPtr (cname, "");
  Constant *nameptr = createGlobalStringPtr (cname);
  return builder.CreateCall (function, nameptr, cname);
}

+(void) insertTrace:(NSString *)message
{
  Constant *function =
    module->getOrInsertFunction ("puts",
                                 Int32Ty,
                                 VoidPointerTy,
                                 NULL);

  builder.CreateCall (function, createGlobalStringPtr ([message UTF8String]));
}

+(void) insertPointerTrace:(Value *)pointerValue
{
  Constant *function =
    module->getOrInsertFunction ("printf",
                                 Int32Ty,
                                 VoidPointerTy,
                                 VoidPointerTy,
                                 NULL);

  builder.CreateCall2 (function,
                       createGlobalStringPtr ("%p\n"),
                       builder.CreateBitCast (pointerValue, VoidPointerTy));
}
@end


@implementation MLKForm (MLKLLVMCompilation)
-(Value *) processForLLVMWithMultiValue:(Value *)multiValue
{
#if 0
  [_compiler insertTrace:
               [NSString stringWithFormat:
                           @"Executing: %@", MLKPrintToString(_form)]];
#endif

  Value *result = [self reallyProcessForLLVMWithMultiValue:multiValue];

#if 0
  [_compiler insertTrace:
               [NSString stringWithFormat:
                           @"Done: %@", MLKPrintToString(_form)]];
#endif

  return result;
}

-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  NSLog (@"WARNING: Unrecognised form type: %@", self);
  return NULL;
}
@end


@implementation MLKProgNForm (MLKLLVMCompilation)
-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  NSEnumerator *e = [_bodyForms objectEnumerator];
  MLKForm *form;
  Value *value = ConstantPointerNull::get (VoidPointerTy);
  unsigned int i;

  i = 0;
  while ((form = [e nextObject]))
    {
      i++;
      if (i == [_bodyForms count])
        value = [form processForLLVMWithMultiValue:multiValue];
      else
        value = [form processForLLVMWithMultiValue:NULL];
    }

  return value;
}
@end


@implementation MLKSimpleLoopForm (MLKLLVMCompilation)
-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  NSEnumerator *e = [_bodyForms objectEnumerator];
  MLKForm *form;

  Function *function = builder.GetInsertBlock()->getParent();

  BasicBlock *loopBlock = BasicBlock::Create (llvm_context, "loop", function);
  BasicBlock *joinBlock = BasicBlock::Create (llvm_context, "after_loop");

  builder.CreateBr (loopBlock);
  builder.SetInsertPoint (loopBlock);

  while ((form = [e nextObject]))
    {
      [form processForLLVMWithMultiValue:NULL];
    }

  builder.CreateBr (loopBlock);
  builder.SetInsertPoint (joinBlock);
  function->getBasicBlockList().push_back (joinBlock);

  builder.CreateUnreachable ();

  return ConstantPointerNull::get (VoidPointerTy);;
}
@end


@implementation MLKSymbolForm (MLKLLVMCompilation)
-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  Value *value;

  //NSLog (@"Symbol: %@", MLKPrintToString (_form));
  //[_compiler insertTrace:[NSString stringWithFormat:@"Symbol: %@", _form]];

  if (![_context variableIsLexical:_form])
    {
      //[_compiler insertTrace:@"Dynamic."];
      Value *mlkdynamiccontext = [_compiler insertClassLookup:@"MLKDynamicContext"];
      Value *dynctx = [_compiler insertMethodCall:@"currentContext"
                                 onObject:mlkdynamiccontext];

      LRETAIN (_form);  // FIXME: release
      Value *symbolV = builder.CreateIntToPtr (ConstantInt::get(Int64Ty,
                                                                (uint64_t)_form,
                                                                false),
                                               VoidPointerTy);

      vector<Value *> args (1, symbolV);
      value = [_compiler insertMethodCall:@"valueForSymbol:"
                         onObject:dynctx
                         withArgumentVector:&args];
    }
  else if ([_context variableIsGlobal:_form])
    {
      //[_compiler insertTrace:@"Global."];
      Value *binding = builder.Insert ([_context globalBindingValueForSymbol:_form]);
      value = [_compiler insertMethodCall:@"value" onObject:binding];      
    }
  else if ([_context variableHeapAllocationForSymbol:_form])
    {
      Value *binding = [_context bindingValueForSymbol:_form];
      value = [_compiler insertMethodCall:@"value" onObject:binding];
    }
  else
    {
      value = builder.CreateLoad ([_context valueValueForSymbol:_form],
                                  [MLKPrintToString(_form) UTF8String]);
    }

  return value;
}
@end


@implementation MLKFunctionCallForm (MLKLLVMCompilation)
-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  Value *functionPtr;
  Value *closureDataPtr;
  vector<Value *> args;

  if (![_context symbolNamesFunction:_head])
    {
      NSLog (@"Compiler: Don't know function %@", MLKPrintToString(_head));
      // XXX Issue a style warning.
    }

  if ([_context functionIsGlobal:_head])
    {
      Value *functionCell;
      Value *closureDataCell;

      functionCell = builder.Insert ([_context functionCellValueForSymbol:_head]);
      functionPtr = builder.CreateLoad (functionCell);
      closureDataCell = builder.Insert ([_context closureDataPointerValueForSymbol:_head]);
      closureDataPtr = builder.CreateLoad (closureDataCell);
    }
  else
    {
      Value *binding = [_context functionBindingValueForSymbol:_head];
      // It's important for closure to be an i8* because we need to calculate
      // the GEP offset in terms of bytes.
      Value *closure = builder.CreateBitCast ([_compiler insertMethodCall:@"value" onObject:binding], VoidPointerTy);

#if defined(OBJC_API_VERSION) && OBJC_API_VERSION >= 2
      ptrdiff_t code_offset = ivar_getOffset (class_getInstanceVariable ([MLKCompiledClosure class], "m_code"));
      ptrdiff_t data_offset = ivar_getOffset (class_getInstanceVariable ([MLKCompiledClosure class], "m_data"));
#else
      ptrdiff_t code_offset = offsetof (MLKCompiledClosure, m_code);
      ptrdiff_t data_offset = offsetof (MLKCompiledClosure, m_data);
#endif
      Constant *code_offset_value = ConstantInt::get (Int32Ty, code_offset, false);
      Constant *data_offset_value = ConstantInt::get (Int32Ty, data_offset, false);
      Value *codeptr = builder.CreateGEP (closure, code_offset_value);
      Value *dataptr = builder.CreateGEP (closure, data_offset_value);
      codeptr = builder.CreateBitCast (codeptr, PointerPointerTy, "closure_code_ptr");
      dataptr = builder.CreateBitCast (codeptr, PointerPointerTy, "closure_data_ptr");
      Value *code = builder.CreateLoad (codeptr, "closure_code");
      Value *data = builder.CreateLoad (dataptr, "closure_data");

      std::vector<const Type *> types (2, PointerPointerTy);
      functionPtr = builder.CreateBitCast (code, PointerType::get(FunctionType::get(VoidPointerTy,
                                                                                    types,
                                                                                    true),
                                                                  0));
      closureDataPtr = builder.CreateBitCast (data, PointerPointerTy);
    }

  //[_compiler insertTrace:[NSString stringWithFormat:@"Call: %@", MLKPrintToString(_head)]];
  //[_compiler insertPointerTrace:functionPtr];

  args.push_back (closureDataPtr);
  if (multiValue)
    args.push_back (multiValue);
  else
    args.push_back (ConstantPointerNull::get (PointerPointerTy));

  NSEnumerator *e = [_argumentForms objectEnumerator];
  MLKForm *form;

  while ((form = [e nextObject]))
    {
      args.push_back ([form processForLLVMWithMultiValue:NULL]);
    }

  //GlobalVariable *endmarker = module->getGlobalVariable ("MLKEndOfArgumentsMarker", false);
  //endmarker->setConstant (true);
  //GlobalVariable *endmarker = new GlobalVariable (VoidPointerTy, true, GlobalValue::ExternalWeakLinkage);
  Value *endmarker = builder.CreateIntToPtr (ConstantInt::get(Int64Ty,
                                                              (uint64_t)MLKEndOfArgumentsMarker,
                                                              false),
                                             VoidPointerTy);
  args.push_back (endmarker);

  // If the pointer output here is different from the one above,
  // there's some stack smashing going on.
  //[_compiler insertTrace:[NSString stringWithFormat:@"Now calling: %@.", MLKPrintToString(_head)]];
  //[_compiler insertPointerTrace:functionPtr];

  CallInst *call = builder.CreateCall (functionPtr,
                                       args.begin(),
                                       args.end(),
                                       [MLKPrintToString(_head) UTF8String]);
  call->setCallingConv(CallingConv::C);
  call->setTailCall(true);

  // XXX
  if ([_context functionIsInline:_head])
    {
      // FIXME: What to do here?
      //InlineFunction (call);
    }

  //[_compiler insertTrace:[NSString stringWithFormat:@"%@ done.", MLKPrintToString(_head)]];

  return call;
}
@end


static void
build_simple_function_definition (MLKBodyForm *processed_form,
                                  id _lambdaListName,
                                  Function*& function,
                                  Value*& closure_data,
                                  intptr_t& closure_data_size)
{
  NSArray *_bodyForms = [processed_form bodyForms];
  MLKLexicalContext *_bodyContext = [processed_form bodyContext];
  MLKLexicalContext *_context = [processed_form context];
  id _compiler = [MLKLLVMCompiler class];

  vector <const Type *> argtypes (2, PointerPointerTy);
  FunctionType *ftype = FunctionType::get (VoidPointerTy, argtypes, true);
  function = Function::Create (ftype,
                               Function::InternalLinkage,
                               "a_lisp_closure_body",
                               module);

  Function::arg_iterator args = function->arg_begin();
  Value *closure_data_arg = args++;
  closure_data_arg->setName ("closure_data");
  
  Value *functionMultiValue = args++;
  functionMultiValue->setName ("function_multiple_value_return_pointer");

  BasicBlock *outerBlock = builder.GetInsertBlock ();
  BasicBlock *initBlock = BasicBlock::Create (llvm_context, "init_function", function);
  BasicBlock *loopBlock = BasicBlock::Create (llvm_context, "load_args");
  BasicBlock *loopInitBlock = BasicBlock::Create (llvm_context, "load_args_prelude");
  BasicBlock *joinBlock = BasicBlock::Create (llvm_context, "function_body");
  BasicBlock *lambdaListNewBlock = BasicBlock::Create (llvm_context, "lambda_list_new");
  BasicBlock *lambdaListUpdateBlock = BasicBlock::Create (llvm_context, "lambda_list_update");

  // ***** HANDLE CLOSURE VARIABLES *****
  builder.SetInsertPoint (outerBlock);

  NSArray *freeVariables = [[processed_form freeVariables] allObjects];
  closure_data = builder.CreateAlloca (VoidPointerTy,
                                       ConstantInt::get(Int32Ty,
                                                        (uint32_t)[freeVariables count],
                                                        false));
  closure_data_size = 0;
  unsigned int i;
  for (i = 0; i < [freeVariables count]; i++)
    {
      // FIXME: We assume heap allocation for all closure variables.
      MLKSymbol *symbol = [freeVariables objectAtIndex:i];
      if (![_context variableIsGlobal:symbol])
        {
          Constant *position = ConstantInt::get(Int32Ty, closure_data_size, false);

          // Fill in the closure data array.
          builder.SetInsertPoint (outerBlock);
          Value *binding = [_context bindingValueForSymbol:symbol];
          Value *closure_value_ptr = builder.CreateGEP (closure_data, position);
          builder.CreateStore (binding, closure_value_ptr);

          // Access the closure data array from within the closure.
          builder.SetInsertPoint (initBlock);
          Value *local_closure_value_ptr = builder.CreateGEP (closure_data_arg,
                                                              position);
          Value *local_closure_value = builder.CreateLoad (local_closure_value_ptr,
                                                           [MLKPrintToString(symbol) UTF8String]);
          [_bodyContext locallySetBindingValue:local_closure_value
                        forSymbol:symbol];

          closure_data_size++;
        }
    }


  // ***** HANDLE ARGUMENTS *****
  builder.SetInsertPoint (initBlock);
  Value *endmarker = builder.CreateIntToPtr (ConstantInt::get(Int64Ty,
                                                              (uint64_t)MLKEndOfArgumentsMarker,
                                                              false),
                                             PointerType::get(Int8Ty, 0));

  Value *ap = builder.CreateAlloca (VoidPointerTy, NULL, "ap");
  Value *ap2 = builder.CreateBitCast (ap, VoidPointerTy);

  builder.CreateCall (module->getOrInsertFunction ("llvm.va_start",
                                                   VoidTy,
                                                   VoidPointerTy,
                                                   NULL),
                      ap2);

  Value *mlkcons = [_compiler insertClassLookup:@"MLKCons"];

  // FIXME: Heap-allocate if appropriate.
  Value *lambdaList = builder.CreateAlloca (VoidPointerTy, NULL, "lambda_list");
  Value *lambdaListTail = builder.CreateAlloca (VoidPointerTy, NULL, "lambda_list_tail");

  builder.CreateStore (ConstantPointerNull::get (VoidPointerTy), lambdaList);
  builder.CreateStore (ConstantPointerNull::get (VoidPointerTy), lambdaListTail);

  builder.CreateBr (loopInitBlock);
  builder.SetInsertPoint (loopInitBlock);
  function->getBasicBlockList().push_back (loopInitBlock);

  Value *arg = builder.CreateVAArg (ap, VoidPointerTy, "arg");
  Value *cond = builder.CreateICmpEQ (arg, endmarker);
  builder.CreateCondBr (cond, joinBlock, loopBlock);
  builder.SetInsertPoint (loopBlock);
  function->getBasicBlockList().push_back (loopBlock);

  builder.CreateCondBr (builder.CreateICmpEQ (builder.CreateLoad (lambdaList),
                                              ConstantPointerNull::get (VoidPointerTy)),
                        lambdaListNewBlock,
                        lambdaListUpdateBlock);

  builder.SetInsertPoint (lambdaListNewBlock);
  function->getBasicBlockList().push_back (lambdaListNewBlock);
  vector <Value *> argv (1, arg);
  argv.push_back (ConstantPointerNull::get (VoidPointerTy));
  Value *newLambdaList = [_compiler insertMethodCall:@"cons:with:"
                                    onObject:mlkcons
                                    withArgumentVector:&argv];
  builder.CreateStore (newLambdaList, lambdaList);
  builder.CreateStore (newLambdaList, lambdaListTail);
  builder.CreateBr (loopInitBlock);

  builder.SetInsertPoint (lambdaListUpdateBlock);
  function->getBasicBlockList().push_back (lambdaListUpdateBlock);

  Value *newCons = [_compiler insertMethodCall:@"cons:with:"
                              onObject:mlkcons
                              withArgumentVector:&argv];
  vector <Value *> setcdr_argv (1, newCons);
  [_compiler insertVoidMethodCall:@"setCdr:"
             onObject:builder.CreateLoad(lambdaListTail)
             withArgumentVector:&setcdr_argv];
  builder.CreateStore (newCons, lambdaListTail);
  builder.CreateBr (loopInitBlock);

  builder.SetInsertPoint (joinBlock);
  function->getBasicBlockList().push_back (joinBlock);

  builder.CreateCall (module->getOrInsertFunction ("llvm.va_end",
                                                   VoidTy,
                                                   VoidPointerTy,
                                                   NULL),
                      ap2);

  if ([_bodyContext variableHeapAllocationForSymbol:_lambdaListName])
    {
      Value *mlkbinding = [_compiler insertClassLookup:@"MLKBinding"];
      Value *currentLambdaList = builder.CreateLoad (lambdaList);
      vector<Value *> args (1, currentLambdaList);
      Value *lambdaBinding = [_compiler insertMethodCall:@"bindingWithValue:"
                                        onObject:mlkbinding
                                        withArgumentVector:&args];
      [_bodyContext setBindingValue:lambdaBinding
                    forSymbol:_lambdaListName];
    }
  else
    [_bodyContext setValueValue:lambdaList forSymbol:_lambdaListName];

  NSEnumerator *e = [_bodyForms objectEnumerator];
  MLKForm *form;
  Value *value = NULL;

  if ([_bodyForms count] == 0)
    {
      //NSLog (@"%LAMBDA: No body.");
      value = ConstantPointerNull::get (VoidPointerTy);
    }

  i = 0;
  while ((form = [e nextObject]))
    {
      i++;
      if (i == [_bodyForms count])
        value = [form processForLLVMWithMultiValue:functionMultiValue];
      else
        value = [form processForLLVMWithMultiValue:NULL];
    }

  builder.CreateRet (value);

  //function->dump();
  //NSLog (@"Verify...");
  verifyFunction (*function);
  //NSLog (@"Optimise...");
  fpm->run (*function);
  //NSLog (@"Assemble...");
  // Explicit assembly is needed in order to allow libffi to call
  // the function.
  execution_engine->getPointerToFunction (function);
  //NSLog (@"Done.");
  //function->dump();
  //function->viewCFG();
  //NSLog (@"Function built.");

  builder.SetInsertPoint (outerBlock);
}


@implementation MLKSimpleLambdaForm (MLKLLVMCompilation)
-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  intptr_t closure_data_size;
  Function *function;
  Value *closure_data;

  build_simple_function_definition (self, _lambdaListName, function, closure_data, closure_data_size);

  vector<Value *> argv;
  argv.push_back (function);
  argv.push_back (builder.CreateBitCast (closure_data, VoidPointerTy));
  argv.push_back (builder.CreateIntToPtr (ConstantInt::get(Int32Ty,
                                                           closure_data_size,
                                                           false),
                                          VoidPointerTy));
  Value *mlkcompiledclosure = [_compiler
                                insertClassLookup:@"MLKCompiledClosure"];
  Value *closure =
    [_compiler insertMethodCall:@"closureWithCode:data:length:"
               onObject:mlkcompiledclosure
               withArgumentVector:&argv];

  return closure;
}
@end


@implementation MLKLetForm (MLKLLVMCompilation)
-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  NSEnumerator *e = [_variableBindingForms objectEnumerator];
  Value *value = ConstantPointerNull::get (VoidPointerTy);
  MLKForm *form;
  MLKVariableBindingForm *binding_form;

  while ((binding_form = [e nextObject]))
    {
      Value *binding_value = [[binding_form valueForm] processForLLVMWithMultiValue:NULL];

      if ([_bodyContext variableHeapAllocationForSymbol:[binding_form name]])
        {
          Value *mlkbinding = [_compiler insertClassLookup:@"MLKBinding"];
          vector<Value *> args (1, binding_value);
          Value *binding = [_compiler insertMethodCall:@"bindingWithValue:"
                                      onObject:mlkbinding
                                      withArgumentVector:&args];
          [_bodyContext setBindingValue:binding
                        forSymbol:[binding_form name]];
        }
      else
        {
          Value *binding_variable = builder.CreateAlloca (VoidPointerTy,
                                                          NULL,
                                                          [(MLKPrintToString([binding_form name]))
                                                            UTF8String]);
          builder.CreateStore (binding_value, binding_variable);

          [_bodyContext setValueValue:binding_variable
                        forSymbol:[binding_form name]];
        }
    }

  unsigned int i = 0;
  e = [_bodyForms objectEnumerator];
  while ((form = [e nextObject]))
    {
      i++;
      if (i == [_bodyForms count])
        value = [form processForLLVMWithMultiValue:multiValue];
      else
        value = [form processForLLVMWithMultiValue:NULL];
    }

  return value;
}
@end


@implementation MLKSimpleFletForm (MLKLLVMCompilation)
-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  NSEnumerator *e = [_functionBindingForms objectEnumerator];
  Value *value = ConstantPointerNull::get (VoidPointerTy);
  MLKForm *form;
  MLKSimpleFunctionBindingForm *binding_form;
  unsigned int i;
  
  while ((binding_form = [e nextObject]))
    {
      intptr_t closure_data_size;
      Function *function;
      Value *closure_data;
      
      build_simple_function_definition (binding_form, [binding_form lambdaListName], function, closure_data, closure_data_size);
      
      vector<Value *> argv;
      argv.push_back (function);
      argv.push_back (builder.CreateBitCast (closure_data, VoidPointerTy));
      argv.push_back (builder.CreateIntToPtr (ConstantInt::get(Int32Ty,
                                                               closure_data_size,
                                                               false),
                                              VoidPointerTy));
      Value *mlkcompiledclosure = [_compiler
                                   insertClassLookup:@"MLKCompiledClosure"];
      Value *closure =
        [_compiler insertMethodCall:@"closureWithCode:data:length:"
                           onObject:mlkcompiledclosure
                 withArgumentVector:&argv];

      Value *binding_value = closure;

      Value *mlkbinding = [_compiler insertClassLookup:@"MLKBinding"];
      vector<Value *> args (1, binding_value);
      Value *binding = [_compiler insertMethodCall:@"bindingWithValue:"
                                          onObject:mlkbinding
                                withArgumentVector:&args];
      [_bodyContext setFunctionBindingValue:binding
                                  forSymbol:[binding_form name]];
    }

  i = 0;
  e = [_bodyForms objectEnumerator];
  while ((form = [e nextObject]))
    {
      i++;
      if (i == [_bodyForms count])
        value = [form processForLLVMWithMultiValue:multiValue];
      else
        value = [form processForLLVMWithMultiValue:NULL];
    }
  
  return value;
}
@end


@implementation MLKQuoteForm (MLKLLVMCompilation)
-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  // FIXME: When to release _quotedData?  At the same time the code is
  // released, probably...
  // FIXME: In garbage-collected code, _quotedData will be deleted even
  // though it is referenced by compiled code!
  LRETAIN (_quotedData);
#ifdef __OBJC_GC__
  if (_quotedData && MLKInstanceP (_quotedData))
    [[NSGarbageCollector defaultCollector] disableCollectorForPointer:_quotedData];
#endif

  return builder.CreateIntToPtr (ConstantInt::get(Int64Ty,
                                                  (uint64_t)_quotedData,
                                                  false),
                                 VoidPointerTy);
}
@end


@implementation MLKSelfEvaluatingForm (MLKLLVMCompilation)
-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  // FIXME: When to release _form?  At the same time the code is
  // released, probably...
  // FIXME: In garbage-collected code, _form will be deleted even
  // though it is referenced by compiled code!
  LRETAIN (_form);
#ifdef __OBJC_GC__
  if (_form && MLKInstanceP (_form))
    [[NSGarbageCollector defaultCollector] disableCollectorForPointer:_form];
#endif

  return builder.CreateIntToPtr (ConstantInt::get(Int64Ty,
                                                  (uint64_t)_form,
                                                  false),
                                 VoidPointerTy);
}
@end


@implementation MLKIfForm (MLKLLVMCompilation)
-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  Function *function = builder.GetInsertBlock()->getParent();
  BasicBlock *thenBlock = BasicBlock::Create (llvm_context, "if_then", function);
  BasicBlock *elseBlock = BasicBlock::Create (llvm_context, "if_else");
  BasicBlock *joinBlock = BasicBlock::Create (llvm_context, "if_join");

  Value *test = builder.CreateICmpNE ([_conditionForm processForLLVMWithMultiValue:NULL],
                                      ConstantPointerNull::get (VoidPointerTy));
  Value *value = builder.CreateAlloca (VoidPointerTy, NULL, "if_result");
  builder.CreateCondBr (test, thenBlock, elseBlock);

  builder.SetInsertPoint (thenBlock);
  builder.CreateStore ([_consequentForm processForLLVMWithMultiValue:multiValue], value);
  builder.CreateBr (joinBlock);

  builder.SetInsertPoint (elseBlock);
  function->getBasicBlockList().push_back (elseBlock);
  builder.CreateStore ([_alternativeForm processForLLVMWithMultiValue:multiValue], value);
  builder.CreateBr (joinBlock);

  builder.SetInsertPoint (joinBlock);
  function->getBasicBlockList().push_back (joinBlock);

  return builder.CreateLoad (value);
}
@end


@implementation MLKSetQForm (MLKLLVMCompilation)
-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  NSEnumerator *var_e, *value_e;
  MLKForm *valueForm;
  Value *value = ConstantPointerNull::get (VoidPointerTy);
  id variable;

  var_e = [_variables objectEnumerator];
  value_e = [_valueForms objectEnumerator];
  while ((valueForm = [value_e nextObject]))
    {
      variable = [var_e nextObject];
      value = [valueForm processForLLVMWithMultiValue:NULL];
      if (![_context variableIsLexical:variable])
        {
          Value *mlkdynamiccontext = [_compiler insertClassLookup:@"MLKDynamicContext"];
          Value *dynctx = [_compiler insertMethodCall:@"currentContext"
                                     onObject:mlkdynamiccontext];

          LRETAIN (variable);  // FIXME: release
#ifdef __OBJC_GC__
          // FIXME: proper memory management
          if (variable && MLKInstanceP (variable))
            [[NSGarbageCollector defaultCollector] disableCollectorForPointer:variable];
#endif

          Value *symbolV = builder.CreateIntToPtr (ConstantInt::get(Int64Ty,
                                                                    (uint64_t)variable,
                                                                    false),
                                                   VoidPointerTy);

          vector<Value *> args;
          args.push_back (symbolV);
          Value *binding = [_compiler insertMethodCall:@"bindingForSymbol:"
                                              onObject:dynctx
                                    withArgumentVector:&args];

          // Test whether the binding is non-null.  If so, set its value, else create a new one.

          Function *function = builder.GetInsertBlock()->getParent();
          BasicBlock *setBlock = BasicBlock::Create (llvm_context, "setq_set_existing_dynamic_binding", function);
          BasicBlock *makeNewBlock = BasicBlock::Create (llvm_context, "setq_make_new_dynamic_binding");
          BasicBlock *joinBlock = BasicBlock::Create (llvm_context, "setq_join");

          Value *test = builder.CreateICmpNE (binding, ConstantPointerNull::get (VoidPointerTy));
          //Value *value = builder.CreateAlloca (VoidPointerTy, NULL, "if_result");
          builder.CreateCondBr (test, setBlock, makeNewBlock);

          builder.SetInsertPoint (setBlock);
          args[0] = value;
          [_compiler insertMethodCall:@"setValue:"
                             onObject:binding
                   withArgumentVector:&args];
          builder.CreateBr (joinBlock);

          builder.SetInsertPoint (makeNewBlock);
          function->getBasicBlockList().push_back (makeNewBlock);
          Value *globalctx = [_compiler insertMethodCall:@"globalContext"
                                                onObject:mlkdynamiccontext];
          args[0] = value;
          args.push_back (symbolV);
          [_compiler insertMethodCall:@"addValue:forSymbol:"
                             onObject:globalctx
                   withArgumentVector:&args];
          builder.CreateBr (joinBlock);

          builder.SetInsertPoint (joinBlock);
          function->getBasicBlockList().push_back (joinBlock);
        }
      else if ([_context variableIsGlobal:variable])
        {
          Value *binding = builder.Insert ([_context globalBindingValueForSymbol:variable]);
          vector<Value *> args (1, value);

          [_compiler insertVoidMethodCall:@"setValue:"
                     onObject:binding
                     withArgumentVector:&args];
        }
      else if ([_context variableHeapAllocationForSymbol:variable])
        {
          Value *binding = [_context bindingValueForSymbol:variable];
          vector<Value *> args (1, value);

          [_compiler insertVoidMethodCall:@"setValue:"
                     onObject:binding
                     withArgumentVector:&args];
        }
      else
        {
          builder.CreateStore (value, [_context valueValueForSymbol:variable]);
        }
    }

  return value;
}
@end


@implementation MLKInPackageForm (MLKLLVMCompilation)
-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  id package = [MLKPackage findPackage:stringify(_packageDesignator)];

  [[MLKDynamicContext currentContext]
    setValue:package
    forSymbol:[[MLKPackage findPackage:@"COMMON-LISP"]
                intern:@"*PACKAGE*"]];

  return builder.CreateIntToPtr (ConstantInt::get(Int64Ty,
                                                  (uint64_t)package,
                                                  false),
                                 VoidPointerTy);
}
@end


@implementation MLKSimpleFunctionForm (MLKLLVMCompilation)
-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  if ([_context functionIsGlobal:_functionName])
    {
      Value *mlklexicalenvironment = [_compiler insertClassLookup:@"MLKLexicalEnvironment"];
      Value *env = [_compiler insertMethodCall:@"globalEnvironment"
                                      onObject:mlklexicalenvironment];

      LRETAIN (_functionName);  // FIXME: release
#ifdef __OBJC_GC__
      // FIXME: proper memory management
      if (_functionName && MLKInstanceP (_functionName))
        [[NSGarbageCollector defaultCollector] disableCollectorForPointer:_functionName];
#endif
      
      Value *symbolV = builder.CreateIntToPtr (ConstantInt::get(Int64Ty,
                                                                (uint64_t)_functionName,
                                                                false),
                                               VoidPointerTy);

      vector<Value *> args;
      args.push_back (symbolV);
      Value *fun = [_compiler insertMethodCall:@"functionForSymbol:"
                                      onObject:env
                            withArgumentVector:&args];
      return fun;
    }
  else
    {
      Value *binding = [_context functionBindingValueForSymbol:_functionName];
      Value *closure = builder.CreateBitCast ([_compiler insertMethodCall:@"value" onObject:binding], VoidPointerTy);

      return closure;
    }
}
@end


@implementation MLKLambdaFunctionForm (MLKLLVMCompilation)
-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  return [_lambdaForm processForLLVMWithMultiValue:multiValue];
}
@end


@implementation MLKMultipleValueListForm (MLKLLVMCompilation)
-(Value *) reallyProcessForLLVMWithMultiValue:(Value *)multiValue
{
  Value *endmarker = builder.CreateIntToPtr (ConstantInt::get(Int64Ty,
                                                              (uint64_t)MLKEndOfArgumentsMarker,
                                                              false),
                                             VoidPointerTy);
  Value *multi_tmp = builder.CreateAlloca (VoidPointerTy, NULL);
  builder.CreateStore (endmarker, multi_tmp);

  Value *value = [_listForm processForLLVMWithMultiValue:multi_tmp];
  Value *return_value = builder.CreateAlloca (VoidPointerTy, NULL);

  Function *function = builder.GetInsertBlock()->getParent();
  BasicBlock *singleValueBlock = BasicBlock::Create (llvm_context, "single_value_block", function);
  BasicBlock *multipleValueBlock = BasicBlock::Create (llvm_context, "multiple_value_block");
  BasicBlock *joinBlock = BasicBlock::Create (llvm_context, "join_block");

  Value *multi_tmp_content = builder.CreateLoad (multi_tmp);
  Value *isSingleValue = builder.CreateICmpEQ (multi_tmp_content, endmarker);
  builder.CreateCondBr (isSingleValue, singleValueBlock, multipleValueBlock);

  builder.SetInsertPoint (singleValueBlock);
  Value *mlkcons = [_compiler insertClassLookup:@"MLKCons"];
  vector <Value *> argv;
  argv.push_back (value);
  argv.push_back (ConstantPointerNull::get (VoidPointerTy));
  Value *newList = [_compiler insertMethodCall:@"cons:with:"
                                      onObject:mlkcons
                            withArgumentVector:&argv];
  builder.CreateStore (newList, return_value);
  builder.CreateBr (joinBlock);

  function->getBasicBlockList().push_back (multipleValueBlock);
  builder.SetInsertPoint (multipleValueBlock);
  builder.CreateStore (multi_tmp_content, return_value);
  builder.CreateBr (joinBlock);

  function->getBasicBlockList().push_back (joinBlock);
  builder.SetInsertPoint (joinBlock);

  return builder.CreateLoad (return_value);
}
@end