qbe.c (69344B)
1 #include "util.h" 2 #include "cc.h" 3 #include <assert.h> 4 #include <ctype.h> 5 #include <inttypes.h> 6 #include <stdbool.h> 7 #include <stdio.h> 8 #include <stdlib.h> 9 #include <string.h> 10 11 struct value { 12 enum { 13 VALUE_NONE, 14 VALUE_GLOBAL, 15 VALUE_INTCONST, 16 VALUE_FLTCONST, 17 VALUE_DBLCONST, 18 VALUE_TEMP, 19 VALUE_TYPE, 20 VALUE_LABEL, 21 22 VALUE_EXTERN = 1 << 4, 23 VALUE_THREAD = 1 << 5, 24 VALUE_QUOTE = 1 << 6, 25 } kind; 26 unsigned id; 27 union { 28 const char *name; 29 unsigned long long i; 30 double f; 31 } u; 32 }; 33 34 struct lvalue { 35 struct value *addr; 36 struct bitfield bits; 37 }; 38 39 enum instkind { 40 INONE, 41 42 #define OP(op, name) op, 43 #include "ops.h" 44 #undef OP 45 46 IARG, 47 IVARARG, 48 }; 49 50 struct qbetype { 51 char base, data; 52 enum instkind load, store; 53 }; 54 55 struct inst { 56 enum instkind kind; 57 int class; 58 struct value res, *arg[2]; 59 }; 60 61 struct jump { 62 enum { 63 JUMP_NONE, 64 JUMP_JMP, 65 JUMP_JNZ, 66 JUMP_RET, 67 JUMP_HLT, 68 } kind; 69 struct value *arg; 70 struct block *blk[2]; 71 }; 72 73 struct block { 74 struct value label; 75 struct array insts; 76 struct { 77 int class; 78 struct block *blk[2]; 79 struct value *val[2]; 80 struct value res; 81 } phi; 82 struct jump jump; 83 84 struct block *next; 85 }; 86 87 struct switchcase { 88 struct treenode node; 89 struct block *body; 90 }; 91 92 struct func { 93 struct decl *decl, *namedecl; 94 char *name; 95 struct value *paramtemps; 96 struct type *type; 97 struct block *start, *end; 98 struct map gotos; 99 unsigned lastid; 100 }; 101 102 static const int ptrclass = 'l'; 103 104 void 105 switchcase(struct switchcases *cases, unsigned long long i, struct block *b) 106 { 107 struct switchcase *c; 108 109 c = treeinsert(&cases->root, i, sizeof(*c)); 110 if (!c->node.new) 111 error(&tok.loc, "multiple 'case' labels with same value"); 112 c->body = b; 113 } 114 115 /* values */ 116 117 struct block * 118 mkblock(char *name) 119 { 120 static unsigned id; 121 struct block *b; 122 123 b = xmalloc(sizeof(*b)); 124 b->label.kind = VALUE_LABEL; 125 b->label.u.name = name; 126 b->label.id = ++id; 127 b->insts = (struct array){0}; 128 b->jump.kind = JUMP_NONE; 129 b->phi.res.kind = VALUE_NONE; 130 b->next = NULL; 131 132 return b; 133 } 134 135 struct value * 136 mkglobal(struct decl *d) 137 { 138 static unsigned id; 139 struct value *v; 140 141 v = xmalloc(sizeof(*v)); 142 v->kind = VALUE_GLOBAL; 143 if (d->linkage == LINKEXTERN) 144 v->kind |= VALUE_EXTERN; 145 if (d->kind == DECLOBJECT && d->u.obj.storage == SDTHREAD) 146 v->kind |= VALUE_THREAD; 147 if (d->asmname) { 148 v->kind |= VALUE_QUOTE; 149 v->u.name = d->asmname; 150 v->id = 0; 151 } else { 152 v->u.name = d->name; 153 v->id = d->linkage == LINKNONE ? ++id : 0; 154 } 155 156 return v; 157 } 158 159 /* extern reference to a plain-named runtime symbol with no struct decl 160 * behind it, since nothing in the translation unit ever declares one: 161 * the linker resolves it against aruu's own runtime (shared/libatomic 162 * for the atomic builtins, shared/libint128 for __int128 multiply and 163 * divide) */ 164 static struct value * 165 mkextfn(const char *name) 166 { 167 struct value *v = xmalloc(sizeof(*v)); 168 v->kind = VALUE_GLOBAL | VALUE_EXTERN; 169 v->id = 0; 170 v->u.name = name; 171 return v; 172 } 173 174 /* size-suffixed atomic runtime symbol (__atomic_load_4, 175 * __atomic_fetch_add_8, ...). 4 and 8 byte pointees only so far */ 176 static struct value * 177 mkatomicfn(struct type *pointee, const char *base) 178 { 179 char *name; 180 int size = pointee->size; 181 182 if (size != 4 && size != 8) 183 error(&tok.loc, "atomic builtins on %d-byte types are not yet supported", size); 184 name = xmalloc(strlen(base) + 3); 185 sprintf(name, "%s_%d", base, size); 186 return mkextfn(name); 187 } 188 189 struct value * 190 mkintconst(unsigned long long n) 191 { 192 struct value *v; 193 194 v = xmalloc(sizeof(*v)); 195 v->kind = VALUE_INTCONST; 196 v->u.i = n; 197 198 return v; 199 } 200 201 static struct value * 202 mkfltconst(int kind, double n) 203 { 204 struct value *v; 205 206 v = xmalloc(sizeof(*v)); 207 v->kind = kind; 208 v->u.f = n; 209 210 return v; 211 } 212 213 static struct qbetype 214 qbetype(struct type *t) 215 { 216 static const struct qbetype ub = {'w', 'b', ILOADUB, ISTOREB}, sb = {'w', 'b', ILOADSB, ISTOREB}, 217 uh = {'w', 'h', ILOADUH, ISTOREH}, sh = {'w', 'h', ILOADSH, ISTOREH}, 218 w = {'w', 'w', ILOADW, ISTOREW}, l = {'l', 'l', ILOADL, ISTOREL}, 219 s = {'s', 's', ILOADS, ISTORES}, d = {'d', 'd', ILOADD, ISTORED}, 220 v = {0}; 221 222 if (t == &typevoid) 223 return v; 224 /* __int128 is arithmetic (PROPSCALAR) but, like a struct, has no 225 * qbe class of its own: every __int128 value is an address (see 226 * funcload/funcstore), so it takes the same l class an aggregate 227 * gets below */ 228 if (!(t->prop & PROPSCALAR) || t->kind == TYPEINT128) 229 return l; 230 switch (t->size) { 231 case 1: 232 return t->u.arith.issigned ? sb : ub; 233 case 2: 234 return t->u.arith.issigned ? sh : uh; 235 case 4: 236 return t->prop & PROPFLOAT ? s : w; 237 case 8: 238 return t->prop & PROPFLOAT ? d : l; 239 case 16: 240 fatal("long double is not yet supported"); 241 } 242 assert(0); 243 } 244 245 /* functions */ 246 247 static void emittype(struct type *); 248 static void emitname(struct value *); 249 static void emitvalue(struct value *); 250 251 static void 252 functemp(struct func *f, struct value *v) 253 { 254 v->kind = VALUE_TEMP; 255 v->u.name = NULL; 256 v->id = ++f->lastid; 257 } 258 259 static const char *const instname[] = { 260 #define OP(op, name) [op] = name, 261 #include "ops.h" 262 #undef OP 263 }; 264 265 static struct inst * 266 mkinst(struct func *f, int op, int class, struct value *arg0, struct value *arg1) 267 { 268 struct inst *inst; 269 270 inst = xmalloc(sizeof(*inst)); 271 inst->kind = op; 272 inst->class = class; 273 inst->arg[0] = arg0; 274 inst->arg[1] = arg1; 275 if (class && op != IARG) 276 functemp(f, &inst->res); 277 else 278 inst->res.kind = VALUE_NONE; 279 return inst; 280 } 281 282 static struct value * 283 funcinst(struct func *f, int op, int class, struct value *arg0, struct value *arg1) 284 { 285 struct inst *inst; 286 struct block *b; 287 288 if (f->end->jump.kind) { 289 b = mkblock("dead"); 290 funclabel(f, b); 291 } 292 inst = mkinst(f, op, class, arg0, arg1); 293 arrayaddptr(&f->end->insts, inst); 294 return &inst->res; 295 } 296 297 static struct value * 298 funcbits(struct func *f, struct type *t, struct value *v, struct bitfield b) 299 { 300 int class, bits; 301 302 class = t->size <= 4 ? 'w' : 'l'; 303 bits = b.after; 304 if (!bits && t->kind == TYPEBITINT) 305 bits = t->size * 8 - t->u.arith.width; 306 if (bits) { 307 bits += (((t->size + 3) & -4) - t->size) << 3; 308 v = funcinst(f, ISHL, class, v, mkintconst(bits)); 309 } 310 bits += b.before; 311 if (bits) 312 v = funcinst(f, t->u.arith.issigned ? ISAR : ISHR, class, v, mkintconst(bits)); 313 return v; 314 } 315 316 struct int128parts { 317 struct value *lo, *hi; 318 }; 319 320 /* a __int128 value is always an address (see funcload/funcstore), so 321 * every operator on one starts by pulling its two 64 bit words out 322 * of memory */ 323 static struct int128parts 324 load128(struct func *f, struct value *addr) 325 { 326 struct int128parts p; 327 p.lo = funcinst(f, ILOADL, 'l', addr, NULL); 328 p.hi = funcinst(f, ILOADL, 'l', funcinst(f, IADD, 'l', addr, mkintconst(8)), NULL); 329 return p; 330 } 331 332 /* mirror of load128: stores lo/hi into a fresh 16 byte slot and 333 * returns its address, the result every __int128 operator produces */ 334 static struct value * 335 store128(struct func *f, struct value *lo, struct value *hi) 336 { 337 struct value *addr = funcinst(f, IALLOC16, ptrclass, mkintconst(16), NULL); 338 funcinst(f, ISTOREL, 0, lo, addr); 339 funcinst(f, ISTOREL, 0, hi, funcinst(f, IADD, 'l', addr, mkintconst(8))); 340 return addr; 341 } 342 343 struct int128cmp { 344 struct value *lt, *eq; /* both 0 or 1, 'l' class */ 345 }; 346 347 /* branchless 128 bit compare: compares the high words first (signed 348 * or unsigned per issigned) and only falls back to an unsigned low 349 * word compare when the high words are equal, the standard technique 350 * for ordering a multi-word integer with no way to chain a carry/ 351 * borrow flag between two independent qbe compare instructions */ 352 static struct int128cmp 353 cmp128(struct func *f, struct int128parts a, struct int128parts b, int issigned) 354 { 355 struct int128cmp c; 356 struct value *hi_lt, *hi_eq, *lo_ult; 357 hi_lt = funcinst(f, issigned ? ICSLTL : ICULTL, 'l', a.hi, b.hi); 358 hi_eq = funcinst(f, ICEQL, 'l', a.hi, b.hi); 359 lo_ult = funcinst(f, ICULTL, 'l', a.lo, b.lo); 360 c.lt = funcinst(f, IOR, 'l', hi_lt, funcinst(f, IAND, 'l', hi_eq, lo_ult)); 361 c.eq = funcinst(f, IAND, 'l', hi_eq, funcinst(f, ICEQL, 'l', a.lo, b.lo)); 362 return c; 363 } 364 365 /* __int128 multiply and divide both lower to a call into 366 * shared/libint128/int128_x64.s: qbe has neither a widening multiply 367 * nor any divide wider than 64 bits, and a real division needs a bit 368 * serial long-division loop no ir-level codegen could express, so 369 * both are out of line the same way atomics are (see mkatomicfn) */ 370 static struct value * 371 funcmul128(struct func *f, struct value *l, struct value *r) 372 { 373 struct value *fn, *v; 374 375 emittype(&typeint128); 376 fn = mkextfn("__multi3"); 377 v = funcinst(f, ICALL, 'l', fn, typeint128.value); 378 funcinst(f, IARG, 'l', l, typeint128.value); 379 funcinst(f, IARG, 'l', r, typeint128.value); 380 return v; 381 } 382 383 /* x + mask, then xor mask again: negates a two's complement value 384 * when mask is all-ones, leaves it unchanged when mask is zero. used 385 * both to take a signed __int128's absolute value (mask = its own 386 * sign, replicated across both words) and, afterward, to flip a 387 * division result's sign back without branching on it */ 388 static struct int128parts 389 condneg128(struct func *f, struct int128parts a, struct value *mask) 390 { 391 struct value *sum_lo, *carry, *sum_hi; 392 struct int128parts r; 393 sum_lo = funcinst(f, IADD, 'l', a.lo, mask); 394 carry = funcinst(f, ICULTL, 'l', sum_lo, a.lo); 395 sum_hi = funcinst(f, IADD, 'l', funcinst(f, IADD, 'l', a.hi, mask), carry); 396 r.lo = funcinst(f, IXOR, 'l', sum_lo, mask); 397 r.hi = funcinst(f, IXOR, 'l', sum_hi, mask); 398 return r; 399 } 400 401 /* / and % on __int128 both call __udivmodti4, which only ever 402 * operates on magnitudes: a signed division negates both operands to 403 * their absolute value first (branchless, the standard mask = hi>>63 404 * trick, reused afterward to flip the quotient's sign when the 405 * operands' signs differed and the remainder's sign to match the 406 * dividend, c's own rule for truncating division) */ 407 static struct value * 408 funcdiv128(struct func *f, struct type *t, struct value *l, struct value *r, int want_remainder) 409 { 410 struct int128parts a, b, ua, ub, qp, rp, res; 411 struct value *fn, *remslot, *uaaddr, *ubaddr, *q, *qmask, *rmask; 412 413 a = load128(f, l); 414 b = load128(f, r); 415 if (t->u.arith.issigned) { 416 struct value *amask = funcinst(f, ISAR, 'l', a.hi, mkintconst(63)); 417 struct value *bmask = funcinst(f, ISAR, 'l', b.hi, mkintconst(63)); 418 ua = condneg128(f, a, amask); 419 ub = condneg128(f, b, bmask); 420 qmask = funcinst(f, IXOR, 'l', amask, bmask); 421 rmask = amask; 422 } else { 423 ua = a; 424 ub = b; 425 qmask = rmask = mkintconst(0); 426 } 427 428 emittype(&typeuint128); 429 /* every value the call arguments reference must be computed before 430 * the icall itself: emitinst's own call-printing groups an icall 431 * with whatever iargs immediately follow it in the block's 432 * instruction list, so nothing (store128's own alloc/store 433 * instructions included) may land between them */ 434 remslot = funcinst(f, IALLOC16, ptrclass, mkintconst(16), NULL); 435 uaaddr = store128(f, ua.lo, ua.hi); 436 ubaddr = store128(f, ub.lo, ub.hi); 437 fn = mkextfn("__udivmodti4"); 438 q = funcinst(f, ICALL, 'l', fn, typeuint128.value); 439 funcinst(f, IARG, 'l', uaaddr, typeuint128.value); 440 funcinst(f, IARG, 'l', ubaddr, typeuint128.value); 441 funcinst(f, IARG, ptrclass, remslot, NULL); 442 443 if (!want_remainder) { 444 qp = load128(f, q); 445 res = condneg128(f, qp, qmask); 446 } else { 447 rp = load128(f, remslot); 448 res = condneg128(f, rp, rmask); 449 } 450 return store128(f, res.lo, res.hi); 451 } 452 453 /* variable count << and >> on __int128: n is a plain 64 bit count (the 454 * shift count keeps its own promoted type instead of converting to 455 * match the shifted operand, per c's own rule for shift operators, so 456 * the caller widens it to 'l' before this point). qbe's shl/shr/sar 457 * mask their count the same way real x86 does, so a shift by exactly 458 * 64 (the one count where "shift the other word by 64-n" would itself 459 * mean shift-by-zero, silently wrong) and a shift by zero (where the 460 * complementary cross-word shift would itself mean shift-by-64) both 461 * need to be routed around the general n-in-1..63 formula rather than 462 * folded into it: two real branches, not a branchless trick */ 463 static struct value * 464 funcshift128(struct func *f, struct type *t, struct value *l, struct value *n, int isleft) 465 { 466 struct int128parts a = load128(f, l); 467 struct block *bzero, *bnz, *bsmall, *blarge, *bnzjoin, *bjoin; 468 enum instkind shrop = t->u.arith.issigned ? ISAR : ISHR; 469 470 bzero = mkblock(isleft ? "shl128_zero" : "shr128_zero"); 471 bnz = mkblock(isleft ? "shl128_nz" : "shr128_nz"); 472 bjoin = mkblock(isleft ? "shl128_join" : "shr128_join"); 473 funcjnz(f, funcinst(f, ICEQL, 'w', n, mkintconst(0)), NULL, bzero, bnz); 474 475 funclabel(f, bzero); 476 bjoin->phi.val[0] = l; /* shift by 0: reuse the operand's own address unchanged */ 477 bjoin->phi.blk[0] = f->end; 478 funcjmp(f, bjoin); 479 480 funclabel(f, bnz); 481 bsmall = mkblock(isleft ? "shl128_small" : "shr128_small"); 482 blarge = mkblock(isleft ? "shl128_large" : "shr128_large"); 483 bnzjoin = mkblock(isleft ? "shl128_nzjoin" : "shr128_nzjoin"); 484 funcjnz(f, funcinst(f, ICULTL, 'w', n, mkintconst(64)), NULL, bsmall, blarge); 485 486 funclabel(f, bsmall); 487 { 488 /* n in 1..63 here: the complementary shift (64-n) is 1..63 too, 489 * never the 0-or-64 counts qbe/x86 would mask away */ 490 struct value *inv = funcinst(f, ISUB, 'l', mkintconst(64), n); 491 struct value *lo, *hi; 492 if (isleft) { 493 hi = 494 funcinst(f, IOR, 'l', funcinst(f, ISHL, 'l', a.hi, n), funcinst(f, ISHR, 'l', a.lo, inv)); 495 lo = funcinst(f, ISHL, 'l', a.lo, n); 496 } else { 497 lo = 498 funcinst(f, IOR, 'l', funcinst(f, ISHR, 'l', a.lo, n), funcinst(f, ISHL, 'l', a.hi, inv)); 499 hi = funcinst(f, shrop, 'l', a.hi, n); 500 } 501 bnzjoin->phi.val[0] = store128(f, lo, hi); 502 bnzjoin->phi.blk[0] = f->end; 503 funcjmp(f, bnzjoin); 504 } 505 506 funclabel(f, blarge); 507 { 508 /* n in 64..127 (n >= 128 is ub, same as any other integer type's 509 * shift by more than its width): the whole low word has already 510 * shifted entirely into, or out of, the high word's position, so 511 * only a single n-64 shift (0..63, safe) is needed */ 512 struct value *nn = funcinst(f, ISUB, 'l', n, mkintconst(64)); 513 struct value *lo, *hi; 514 if (isleft) { 515 hi = funcinst(f, ISHL, 'l', a.lo, nn); 516 lo = mkintconst(0); 517 } else { 518 lo = funcinst(f, shrop, 'l', a.hi, nn); 519 hi = t->u.arith.issigned ? funcinst(f, ISAR, 'l', a.hi, mkintconst(63)) : mkintconst(0); 520 } 521 bnzjoin->phi.val[1] = store128(f, lo, hi); 522 bnzjoin->phi.blk[1] = f->end; 523 funcjmp(f, bnzjoin); 524 } 525 526 funclabel(f, bnzjoin); 527 bnzjoin->phi.class = 'l'; 528 functemp(f, &bnzjoin->phi.res); 529 530 bjoin->phi.val[1] = &bnzjoin->phi.res; 531 bjoin->phi.blk[1] = bnzjoin; 532 funclabel(f, bjoin); 533 bjoin->phi.class = 'l'; 534 functemp(f, &bjoin->phi.res); 535 return &bjoin->phi.res; 536 } 537 538 struct complexparts { 539 struct value *re, *im; 540 }; 541 542 /* same reasoning as load128: a complex value is always an address 543 * (see funcload/funcstore), so every operator on one starts by 544 * pulling its real and imaginary parts, back to back in memory, out 545 * of it. unlike __int128 the two halves are the underlying real 546 * type's own qbe class ('s' or 'd'), not always 'l' */ 547 static struct complexparts 548 loadcomplex(struct func *f, struct type *t, struct value *addr) 549 { 550 struct qbetype qt = qbetype(t->base); 551 struct complexparts p; 552 p.re = funcinst(f, qt.load, qt.base, addr, NULL); 553 p.im = 554 funcinst(f, qt.load, qt.base, funcinst(f, IADD, 'l', addr, mkintconst(t->base->size)), NULL); 555 return p; 556 } 557 558 /* mirror of loadcomplex: stores re/im into a fresh slot sized and 559 * aligned for t and returns its address, the result every complex 560 * operator produces */ 561 static struct value * 562 storecomplex(struct func *f, struct type *t, struct value *re, struct value *im) 563 { 564 struct qbetype qt = qbetype(t->base); 565 struct value *addr = 566 funcinst(f, t->align <= 4 ? IALLOC4 : IALLOC8, ptrclass, mkintconst(t->size), NULL); 567 funcinst(f, qt.store, 0, re, addr); 568 funcinst(f, qt.store, 0, im, funcinst(f, IADD, 'l', addr, mkintconst(t->base->size))); 569 return addr; 570 } 571 572 static struct value * 573 convert(struct func *f, struct type *dst, struct type *src, struct value *l) 574 { 575 enum instkind op; 576 struct value *r = NULL; 577 int class; 578 579 if (src == dst) 580 return l; 581 if (src->kind == TYPEPOINTER) 582 src = &typeulong; 583 if (dst->kind == TYPEPOINTER) 584 dst = &typeulong; 585 if (dst->kind == TYPEVOID) 586 return NULL; 587 if (dst->kind == TYPEINT128 && src->kind == TYPEINT128) 588 return l; /* signed <-> unsigned __int128: identical representation */ 589 if (dst->kind == TYPEINT128) { 590 struct value *lo, *hi; 591 int issigned; 592 if (src->prop & PROPFLOAT) { 593 /* truncate toward zero through a 64 bit intermediate: magnitude 594 * beyond 64 bits is lost, a documented gap rather than a 595 * crash, the same treatment this compiler already gives any 596 * other out-of-range float-to-int conversion */ 597 l = convert(f, dst->u.arith.issigned ? &typelong : &typeulong, src, l); 598 issigned = dst->u.arith.issigned; 599 } else { 600 issigned = src->u.arith.issigned; 601 if (src->size < 8) 602 l = convert(f, issigned ? &typelong : &typeulong, src, l); 603 } 604 lo = l; 605 hi = issigned ? funcinst(f, ISAR, 'l', l, mkintconst(63)) : mkintconst(0); 606 return store128(f, lo, hi); 607 } 608 if (src->kind == TYPEINT128) { 609 struct int128parts p = load128(f, l); 610 if (dst->kind == TYPEBOOL) 611 return funcinst(f, ICNEL, 'w', funcinst(f, IOR, 'l', p.lo, p.hi), mkintconst(0)); 612 /* every other destination depends only on the low word: exact for 613 * any value that fits, a documented magnitude loss otherwise, 614 * left to the same implementation-defined narrowing this compiler 615 * already leaves unchecked for every other lossy int conversion */ 616 return convert(f, dst, src->u.arith.issigned ? &typelong : &typeulong, p.lo); 617 } 618 if (dst->kind == TYPECOMPLEX && src->kind == TYPECOMPLEX) { 619 /* float _Complex <-> double _Complex: convert each component on 620 * its own, same as converting two independent reals */ 621 struct complexparts p = loadcomplex(f, src, l); 622 return storecomplex( 623 f, dst, convert(f, dst->base, src->base, p.re), convert(f, dst->base, src->base, p.im) 624 ); 625 } 626 if (dst->kind == TYPECOMPLEX) { 627 /* real -> complex: imaginary part is exactly 0 */ 628 struct qbetype qt = qbetype(dst->base); 629 return storecomplex( 630 f, 631 dst, 632 convert(f, dst->base, src, l), 633 mkfltconst(qt.base == 's' ? VALUE_FLTCONST : VALUE_DBLCONST, 0) 634 ); 635 } 636 if (src->kind == TYPECOMPLEX) { 637 /* complex -> real: the imaginary part is simply discarded, the 638 * same implementation-defined narrowing real compilers warn about 639 * and this one does not */ 640 struct complexparts p = loadcomplex(f, src, l); 641 return convert(f, dst, src->base, p.re); 642 } 643 if (!(src->prop & PROPREAL) || !(dst->prop & PROPREAL)) 644 fatal("internal error; unsupported conversion"); 645 if (dst->kind == TYPEBOOL) { 646 class = 'w'; 647 if (src->prop & PROPINT) { 648 r = mkintconst(0); 649 switch (src->size) { 650 case 1: 651 op = ICNEW; 652 if (src->kind != TYPEBITINT) 653 l = funcinst(f, IEXTUB, 'w', l, NULL); 654 break; 655 case 2: 656 op = ICNEW; 657 if (src->kind != TYPEBITINT) 658 l = funcinst(f, IEXTUH, 'w', l, NULL); 659 break; 660 case 4: 661 op = ICNEW; 662 break; 663 case 8: 664 op = ICNEL; 665 break; 666 default: 667 fatal( 668 "internal error; unknown integer " 669 "conversion" 670 ); 671 } 672 } else { 673 assert(src->prop & PROPFLOAT); 674 switch (src->size) { 675 case 4: 676 op = ICNES, r = mkfltconst(VALUE_FLTCONST, 0); 677 break; 678 case 8: 679 op = ICNED, r = mkfltconst(VALUE_DBLCONST, 0); 680 break; 681 default: 682 fatal( 683 "internal error; unknown floating point " 684 "conversion" 685 ); 686 } 687 } 688 } else if (dst->prop & PROPINT) { 689 class = dst->size == 8 ? 'l' : 'w'; 690 if (src->prop & PROPINT) { 691 if (dst->u.arith.width <= src->u.arith.width) { 692 if (dst->kind == TYPEBITINT) 693 return funcbits(f, dst, l, (struct bitfield){0}); 694 return l; 695 } 696 if (src->kind == TYPEBITINT && (src->size == 8 || dst->size == 4)) 697 return l; 698 switch (src->size) { 699 case 4: 700 op = src->u.arith.issigned ? IEXTSW : IEXTUW; 701 break; 702 case 2: 703 op = src->u.arith.issigned ? IEXTSH : IEXTUH; 704 break; 705 case 1: 706 op = src->u.arith.issigned ? IEXTSB : IEXTUB; 707 break; 708 default: 709 fatal( 710 "internal error; unknown integer " 711 "conversion" 712 ); 713 } 714 } else { 715 if (dst->u.arith.issigned) 716 op = src->size == 8 ? IDTOSI : ISTOSI; 717 else 718 op = src->size == 8 ? IDTOUI : ISTOUI; 719 } 720 } else { 721 class = dst->size == 8 ? 'd' : 's'; 722 if (src->prop & PROPINT) { 723 if (src->size < 4) 724 l = convert(f, src->u.arith.issigned ? &typeint : &typeuint, src, l); 725 if (src->u.arith.issigned) 726 op = src->size == 8 ? ISLTOF : ISWTOF; 727 else 728 op = src->size == 8 ? IULTOF : IUWTOF; 729 } else { 730 assert(src->prop & PROPFLOAT); 731 if (src->size == dst->size) 732 return l; 733 op = src->size < dst->size ? IEXTS : ITRUNCD; 734 } 735 } 736 737 return funcinst(f, op, class, l, r); 738 } 739 740 static void 741 calcvla(struct func *f, struct type *t) 742 { 743 struct value *length, *basesize; 744 745 if (!(t->prop & PROPVM)) 746 return; 747 if (t->base) 748 calcvla(f, t->base); 749 if (t->kind == TYPEFUNC || t->size) 750 return; 751 assert(t->kind == TYPEARRAY); 752 if (!t->u.array.size) { 753 assert(t->base->size || t->base->kind == TYPEARRAY); 754 assert(t->u.array.length); 755 length = convert(f, &typeulong, t->u.array.length->type, funcexpr(f, t->u.array.length)); 756 basesize = t->base->size ? mkintconst(t->base->size) : t->base->u.array.size; 757 t->u.array.size = funcinst(f, IMUL, 'l', length, basesize); 758 } 759 } 760 761 static void 762 funcalloc(struct func *f, struct decl *d) 763 { 764 enum instkind op; 765 struct block *end; 766 struct value *v; 767 int align; 768 769 assert(!d->type->incomplete); 770 calcvla(f, d->type); 771 end = f->end; 772 if (d->type->size) { 773 f->end = f->start; 774 v = mkintconst(d->type->size); 775 } else { 776 assert(d->type->kind == TYPEARRAY); 777 assert(d->type->u.array.size); 778 v = d->type->u.array.size; 779 } 780 align = d->u.obj.align; 781 switch (align) { 782 case 1: 783 case 2: 784 case 4: 785 op = IALLOC4; 786 break; 787 case 8: 788 op = IALLOC8; 789 break; 790 default: 791 v = funcinst(f, IADD, ptrclass, v, mkintconst(align - 16)); /* fallthrough */ 792 case 16: 793 op = IALLOC16; 794 break; 795 } 796 v = funcinst(f, op, ptrclass, v, NULL); 797 if (align > 16) { 798 /* TODO: implement alloc32 in QBE and use that instead */ 799 v = funcinst(f, IADD, ptrclass, v, mkintconst(align - 16)); 800 v = funcinst(f, IAND, ptrclass, v, mkintconst(-align)); 801 } 802 d->value = v; 803 f->end = end; 804 } 805 806 static void 807 funccopy(struct func *f, struct value *dst, struct value *src, unsigned long long size, int align) 808 { 809 enum instkind load, store; 810 int class; 811 struct value *tmp, *inc; 812 unsigned long long off; 813 814 assert((align & align - 1) == 0); 815 class = 'w'; 816 switch (align) { 817 case 1: 818 load = ILOADUB, store = ISTOREB; 819 break; 820 case 2: 821 load = ILOADUH, store = ISTOREH; 822 break; 823 case 4: 824 load = ILOADW, store = ISTOREW; 825 break; 826 default: 827 load = ILOADL, store = ISTOREL, align = 8, class = 'l'; 828 break; 829 } 830 inc = mkintconst(align); 831 off = 0; 832 for (;;) { 833 tmp = funcinst(f, load, class, src, NULL); 834 funcinst(f, store, 0, tmp, dst); 835 off += align; 836 if (off >= size) 837 break; 838 src = funcinst(f, IADD, ptrclass, src, inc); 839 dst = funcinst(f, IADD, ptrclass, dst, inc); 840 } 841 } 842 843 static struct value * 844 funcstore(struct func *f, struct type *t, enum typequal tq, struct lvalue lval, struct value *v) 845 { 846 struct value *r; 847 enum typeprop tp; 848 unsigned long long mask; 849 struct qbetype qt; 850 int bits; 851 852 if (tq & QUALVOLATILE) 853 error(&tok.loc, "volatile store is not yet supported"); 854 if (tq & QUALCONST) 855 error(&tok.loc, "cannot store to 'const' object"); 856 tp = t->prop; 857 assert(!lval.bits.before && !lval.bits.after || tp & PROPINT); 858 r = v; 859 switch (t->kind) { 860 case TYPESTRUCT: 861 case TYPEUNION: 862 case TYPEARRAY: 863 case TYPEINT128: 864 case TYPECOMPLEX: 865 funccopy(f, lval.addr, v, t->size, t->align); 866 break; 867 case TYPEPOINTER: 868 t = &typeulong; 869 /* fallthrough */ 870 default: 871 assert(tp & PROPSCALAR); 872 qt = qbetype(t); 873 bits = lval.bits.before + lval.bits.after; 874 if (bits) { 875 mask = 0xffffffffffffffffu >> (64 - t->size * 8 + bits) << lval.bits.before; 876 v = funcinst(f, ISHL, qt.base, v, mkintconst(lval.bits.before)); 877 r = funcbits(f, t, v, lval.bits); 878 v = funcinst(f, IAND, qt.base, v, mkintconst(mask)); 879 v = funcinst( 880 f, 881 IOR, 882 qt.base, 883 v, 884 funcinst( 885 f, IAND, qt.base, funcinst(f, qt.load, qt.base, lval.addr, NULL), mkintconst(~mask) 886 ) 887 ); 888 } 889 funcinst(f, qt.store, 0, v, lval.addr); 890 break; 891 } 892 return r; 893 } 894 895 static struct value * 896 funcload(struct func *f, struct type *t, struct lvalue lval) 897 { 898 struct value *v; 899 struct qbetype qt; 900 901 switch (t->kind) { 902 case TYPESTRUCT: 903 case TYPEUNION: 904 case TYPEARRAY: 905 case TYPEINT128: 906 case TYPECOMPLEX: 907 return lval.addr; 908 default: 909 break; 910 } 911 qt = qbetype(t); 912 v = funcinst(f, qt.load, qt.base, lval.addr, NULL); 913 return funcbits(f, t, v, lval.bits); 914 } 915 916 struct func * 917 mkfunc(struct decl *decl, char *name, struct type *t, struct scope *s) 918 { 919 struct func *f; 920 struct decl *d; 921 struct value *v; 922 923 f = xmalloc(sizeof(*f)); 924 f->decl = decl; 925 f->name = name; 926 f->type = t; 927 f->start = f->end = mkblock("start"); 928 f->lastid = 0; 929 mapinit(&f->gotos, 8); 930 emittype(t->base); 931 932 /* allocate space for parameters */ 933 f->paramtemps = xreallocarray(NULL, t->u.func.nparam, sizeof *f->paramtemps); 934 for (d = t->u.func.params, v = f->paramtemps; d; d = d->next, ++v) { 935 emittype(d->type); 936 functemp(f, v); 937 if (!d->name) 938 continue; 939 if (d->type->value) { 940 d->value = v; 941 } else { 942 funcalloc(f, d); 943 funcstore(f, d->type, QUALNONE, (struct lvalue){.addr = d->value}, v); 944 } 945 } 946 947 t = mkarraytype(&typechar, QUALCONST, strlen(name) + 1); 948 d = mkdecl("__func__", DECLOBJECT, t, QUALNONE, LINKNONE); 949 d->u.obj.storage = SDSTATIC; 950 d->value = mkglobal(d); 951 scopeputdecl(s, d); 952 f->namedecl = d; 953 954 funclabel(f, mkblock("body")); 955 956 return f; 957 } 958 959 void 960 delfunc(struct func *f) 961 { 962 struct block *b; 963 struct inst **inst; 964 965 while ((b = f->start)) { 966 f->start = b->next; 967 arrayforeach(&b->insts, inst) free(*inst); 968 free(b->insts.val); 969 free(b); 970 } 971 mapfree(&f->gotos, free); 972 free(f); 973 } 974 975 struct type * 976 functype(struct func *f) 977 { 978 return f->type; 979 } 980 981 void 982 funclabel(struct func *f, struct block *b) 983 { 984 f->end->next = b; 985 f->end = b; 986 } 987 988 void 989 funcjmp(struct func *f, struct block *l) 990 { 991 struct block *b = f->end; 992 993 if (!b->jump.kind) { 994 b->jump.kind = JUMP_JMP; 995 b->jump.blk[0] = l; 996 } 997 } 998 999 void 1000 funcjnz(struct func *f, struct value *v, struct type *t, struct block *l1, struct block *l2) 1001 { 1002 struct block *b = f->end; 1003 1004 if (b->jump.kind) 1005 return; 1006 if (t) { 1007 assert(t->prop & PROPSCALAR); 1008 /* 1009 * ideally we would just do this conversion unconditionally, 1010 * but QBE is not currently able to optimize the conversion 1011 * away for int 1012 */ 1013 if (t->prop & PROPINT && t->size < 4) 1014 v = convert(f, &typeint, t, v); 1015 else if (t->prop & PROPFLOAT || t->size > 4) 1016 v = convert(f, &typebool, t, v); 1017 } 1018 b->jump.kind = JUMP_JNZ; 1019 b->jump.arg = v; 1020 b->jump.blk[0] = l1; 1021 b->jump.blk[1] = l2; 1022 } 1023 1024 void 1025 funcret(struct func *f, struct value *v) 1026 { 1027 struct block *b = f->end; 1028 1029 if (!b->jump.kind) { 1030 b->jump.kind = JUMP_RET; 1031 b->jump.arg = v; 1032 } 1033 } 1034 1035 void 1036 funchlt(struct func *f) 1037 { 1038 struct block *b = f->end; 1039 1040 if (!b->jump.kind) 1041 b->jump.kind = JUMP_HLT; 1042 } 1043 1044 struct gotolabel * 1045 funcgoto(struct func *f, char *name) 1046 { 1047 struct gotolabel *g; 1048 struct mapkey key; 1049 size_t idx; 1050 1051 mapkey(&key, name, strlen(name)); 1052 if (mapput(&f->gotos, &key, &idx)) { 1053 g = xmalloc(sizeof(*g)); 1054 g->label = mkblock(name); 1055 f->gotos.vals[idx].p = g; 1056 } 1057 1058 return f->gotos.vals[idx].p; 1059 } 1060 1061 static struct lvalue 1062 funclval(struct func *f, struct expr *e) 1063 { 1064 struct lvalue lval = {0}; 1065 struct decl *d; 1066 1067 if (e->kind == EXPRBITFIELD) { 1068 lval.bits = e->u.bitfield.bits; 1069 e = e->base; 1070 } 1071 switch (e->kind) { 1072 case EXPRIDENT: 1073 d = e->u.ident.decl; 1074 if (d->kind != DECLOBJECT && d->kind != DECLFUNC) 1075 error(&tok.loc, "identifier '%s' is not an object or function", d->name); 1076 if (d == f->namedecl) { 1077 fputs("data ", stdout); 1078 emitname(d->value); 1079 printf(" = { b \"%s\", b 0 }\n", f->name); 1080 f->namedecl = NULL; 1081 } 1082 lval.addr = d->value; 1083 break; 1084 case EXPRSTRING: 1085 d = stringdecl(e); 1086 lval.addr = d->value; 1087 break; 1088 case EXPRCOMPOUND: 1089 if (e->toeval) 1090 funcexpr(f, e->toeval); 1091 d = e->u.compound.decl; 1092 funcinit(f, d, e->u.compound.init, true); 1093 lval.addr = d->value; 1094 break; 1095 case EXPRUNARY: 1096 if (e->op != TMUL) 1097 error(&tok.loc, "expression is not an object"); 1098 lval.addr = funcexpr(f, e->base); 1099 break; 1100 default: 1101 if (e->type->kind != TYPESTRUCT && e->type->kind != TYPEUNION) 1102 error(&tok.loc, "expression is not an object"); 1103 lval.addr = funcexpr(f, e); 1104 } 1105 return lval; 1106 } 1107 1108 /* returns the expression value in the true branch */ 1109 struct value * 1110 funcbranch(struct func *f, struct expr *e, struct block *bt, struct block *bf) 1111 { 1112 static struct value one = {.kind = VALUE_INTCONST, .u.i = 1}; 1113 struct expr *l, *r; 1114 struct value *v; 1115 struct block *b; 1116 1117 /* maybe we we could do something for EXPRCOND as well */ 1118 switch (e->kind) { 1119 case EXPRBINARY: 1120 l = e->u.binary.l; 1121 r = e->u.binary.r; 1122 switch (e->op) { 1123 case TEQL: 1124 case TNEQ: 1125 r = eval(r); 1126 if (r->kind == EXPRCONST && r->type->prop & PROPINT && r->u.constant.u == 0) { 1127 if (e->op == TEQL) 1128 b = bt, bt = bf, bf = b; 1129 funcbranch(f, l, bt, bf); 1130 return &one; 1131 } 1132 break; 1133 case TLOR: 1134 case TLAND: 1135 if (e->op == TLOR) { 1136 b = mkblock("logic_or"); 1137 funcbranch(f, l, bt, b); 1138 } else { 1139 b = mkblock("logic_and"); 1140 funcbranch(f, l, b, bf); 1141 } 1142 funclabel(f, b); 1143 funcbranch(f, r, bt, bf); 1144 return &one; 1145 default: 1146 break; 1147 } 1148 break; 1149 case EXPRCOMMA: 1150 for (e = e->base; e->next; e = e->next) 1151 funcexpr(f, e); 1152 return funcbranch(f, e, bt, bf); 1153 default: 1154 break; 1155 } 1156 v = funcexpr(f, e); 1157 funcjnz(f, v, e->type, bt, bf); 1158 return v; 1159 } 1160 1161 struct value * 1162 funcexpr(struct func *f, struct expr *e) 1163 { 1164 enum instkind op = INONE; 1165 struct decl *d; 1166 struct value *l, *r, *v, *v2, *fn, **argvals; 1167 struct lvalue lval; 1168 struct expr *arg; 1169 struct block *b[3]; 1170 struct type *t, *functype; 1171 size_t i; 1172 1173 calcvla(f, e->type); 1174 switch (e->kind) { 1175 case EXPRIDENT: 1176 d = e->u.ident.decl; 1177 switch (d->kind) { 1178 case DECLOBJECT: 1179 return funcload(f, e->type, (struct lvalue){.addr = d->value}); 1180 case DECLCONST: 1181 return d->value; 1182 default: 1183 fatal("unimplemented declaration kind %d", d->kind); 1184 } 1185 break; 1186 case EXPRCONST: 1187 t = e->type; 1188 if (t->kind == TYPEINT128) { 1189 /* the frontend's own constant representation is 64 bits wide 1190 * (cc.h's expr.u.constant union), so every __int128 constant 1191 * that reaches here already fits in one word: build the 1192 * address load128/store128 callers expect by sign or zero 1193 * extending it to the high word, rather than handing back the 1194 * bare 64-bit scalar (which funcload/funcstore's own address 1195 * convention for this type would then misread as a pointer) */ 1196 long long lo = e->u.constant.i; 1197 return store128(f, mkintconst(lo), mkintconst(t->u.arith.issigned && lo < 0 ? -1 : 0)); 1198 } 1199 if (t->prop & PROPINT || t->kind == TYPEPOINTER) 1200 return mkintconst(e->u.constant.u); 1201 assert(t->prop & PROPFLOAT); 1202 return mkfltconst(t->size == 4 ? VALUE_FLTCONST : VALUE_DBLCONST, e->u.constant.f); 1203 case EXPRBITFIELD: 1204 case EXPRCOMPOUND: 1205 lval = funclval(f, e); 1206 return funcload(f, e->type, lval); 1207 case EXPRINCDEC: 1208 lval = funclval(f, e->base); 1209 l = funcload(f, e->base->type, lval); 1210 t = e->type; 1211 if (t->kind == TYPEPOINTER) { 1212 if (t->base->kind == TYPEARRAY && t->base->size == 0) { 1213 r = t->base->u.array.size; 1214 } else { 1215 r = mkintconst(t->base->size); 1216 } 1217 } else if (t->prop & PROPINT) { 1218 r = mkintconst(1); 1219 } else if (t->prop & PROPFLOAT) { 1220 r = mkfltconst(t->size == 4 ? VALUE_FLTCONST : VALUE_DBLCONST, 1); 1221 } else { 1222 fatal("not a scalar"); 1223 } 1224 v = funcinst(f, e->op == TINC ? IADD : ISUB, qbetype(t).base, l, r); 1225 v = funcstore(f, e->type, e->qual, lval, v); 1226 return e->u.incdec.post ? l : v; 1227 case EXPRCALL: 1228 argvals = xreallocarray(NULL, e->u.call.nargs, sizeof(argvals[0])); 1229 for (arg = e->u.call.args, i = 0; arg; arg = arg->next, ++i) { 1230 emittype(arg->type); 1231 argvals[i] = funcexpr(f, arg); 1232 } 1233 t = e->type; 1234 emittype(t); 1235 v = funcinst(f, ICALL, qbetype(t).base, funcexpr(f, e->base), t->value); 1236 functype = e->base->type->base; 1237 for (arg = e->u.call.args, i = 0; arg; arg = arg->next, ++i) { 1238 if (functype->u.func.isvararg && i == functype->u.func.nparam) 1239 funcinst(f, IVARARG, 0, NULL, NULL); 1240 t = arg->type; 1241 funcinst(f, IARG, qbetype(t).base, argvals[i], t->value); 1242 } 1243 e = e->base; 1244 if (e->kind == EXPRUNARY && e->op == TBAND) { 1245 e = e->base; 1246 if (e->kind == EXPRIDENT && e->u.ident.decl->u.func.isnoreturn) 1247 funchlt(f); 1248 } 1249 return v; 1250 case EXPRUNARY: 1251 switch (e->op) { 1252 case TBAND: 1253 lval = funclval(f, e->base); 1254 return lval.addr; 1255 case TMUL: 1256 r = funcexpr(f, e->base); 1257 return funcload(f, e->type, (struct lvalue){.addr = r}); 1258 case TSUB: 1259 r = funcexpr(f, e->base); 1260 if (e->type->kind == TYPEINT128) { 1261 /* two's complement negation, same borrow logic as 1262 * TSUB's binary case with lo_a/hi_a fixed at zero */ 1263 struct int128parts a; 1264 struct value *lo, *hi, *carry; 1265 a = load128(f, r); 1266 carry = funcinst(f, ICULTL, 'l', mkintconst(0), a.lo); 1267 lo = funcinst(f, ISUB, 'l', mkintconst(0), a.lo); 1268 hi = funcinst(f, ISUB, 'l', funcinst(f, ISUB, 'l', mkintconst(0), a.hi), carry); 1269 return store128(f, lo, hi); 1270 } 1271 if (e->type->kind == TYPECOMPLEX) { 1272 struct complexparts a; 1273 struct qbetype qt; 1274 a = loadcomplex(f, e->type, r); 1275 qt = qbetype(e->type->base); 1276 return storecomplex( 1277 f, 1278 e->type, 1279 funcinst(f, INEG, qt.base, a.re, NULL), 1280 funcinst(f, INEG, qt.base, a.im, NULL) 1281 ); 1282 } 1283 return funcinst(f, INEG, qbetype(e->type).base, r, NULL); 1284 default: 1285 break; 1286 } 1287 fatal("internal error; unknown unary expression"); 1288 break; 1289 case EXPRCAST: 1290 if (e->toeval) 1291 funcexpr(f, e->toeval); 1292 l = funcexpr(f, e->base); 1293 return convert(f, e->type, e->base->type, l); 1294 case EXPRBINARY: 1295 if (e->op == TLOR || e->op == TLAND) { 1296 b[0] = mkblock("logic_true"); 1297 b[1] = mkblock("logic_false"); 1298 b[2] = mkblock("logic_join"); 1299 1300 funcbranch(f, e, b[0], b[1]); 1301 funclabel(f, b[0]); 1302 funcjmp(f, b[2]); 1303 funclabel(f, b[1]); 1304 1305 b[2]->phi.class = 'w'; 1306 b[2]->phi.blk[0] = b[0]; 1307 b[2]->phi.val[0] = mkintconst(1); 1308 b[2]->phi.blk[1] = b[1]; 1309 b[2]->phi.val[1] = mkintconst(0); 1310 functemp(f, &b[2]->phi.res); 1311 funclabel(f, b[2]); 1312 1313 return &b[2]->phi.res; 1314 } 1315 l = funcexpr(f, e->u.binary.l); 1316 r = funcexpr(f, e->u.binary.r); 1317 t = e->u.binary.l->type; 1318 if (t->kind == TYPEPOINTER) 1319 t = &typeulong; 1320 if (t->kind == TYPEINT128) { 1321 /* qbe has no 128-bit register or op of its own, so a value 1322 * of this type always lives in memory (l/r are addresses, 1323 * see funcload/funcstore) and arithmetic works a word at a 1324 * time. add/sub need a carry/borrow between the low and high 1325 * words: (lo <u lo_a) after an add can only be true if the 1326 * add wrapped past 2**64, the standard software-carry trick 1327 * given no carry flag is reachable from qbe ir. multiply and 1328 * divide call out to shared/libint128 (see funcmul128/ 1329 * funcdiv128) */ 1330 struct int128parts a, b; 1331 struct value *lo, *hi, *carry; 1332 if (e->op == TSHL || e->op == TSHR) { 1333 /* the shift count keeps its own promoted type rather than 1334 * converting to match the shifted operand (c's own rule 1335 * for shift operators), so r here is a plain scalar, never 1336 * a __int128 address like every other operand below */ 1337 struct type *rt = e->u.binary.r->type; 1338 struct value *n = r; 1339 if (rt->kind == TYPEINT128) 1340 n = load128(f, r).lo; 1341 else if (rt->size < 8) 1342 n = funcinst(f, rt->u.arith.issigned ? IEXTSW : IEXTUW, 'l', r, NULL); 1343 return funcshift128(f, t, l, n, e->op == TSHL); 1344 } 1345 a = load128(f, l); 1346 b = load128(f, r); 1347 switch (e->op) { 1348 case TADD: 1349 lo = funcinst(f, IADD, 'l', a.lo, b.lo); 1350 carry = funcinst(f, ICULTL, 'l', lo, a.lo); 1351 hi = funcinst(f, IADD, 'l', funcinst(f, IADD, 'l', a.hi, b.hi), carry); 1352 break; 1353 case TSUB: 1354 carry = funcinst(f, ICULTL, 'l', a.lo, b.lo); 1355 lo = funcinst(f, ISUB, 'l', a.lo, b.lo); 1356 hi = funcinst(f, ISUB, 'l', funcinst(f, ISUB, 'l', a.hi, b.hi), carry); 1357 break; 1358 case TBAND: 1359 lo = funcinst(f, IAND, 'l', a.lo, b.lo); 1360 hi = funcinst(f, IAND, 'l', a.hi, b.hi); 1361 break; 1362 case TBOR: 1363 lo = funcinst(f, IOR, 'l', a.lo, b.lo); 1364 hi = funcinst(f, IOR, 'l', a.hi, b.hi); 1365 break; 1366 case TXOR: 1367 lo = funcinst(f, IXOR, 'l', a.lo, b.lo); 1368 hi = funcinst(f, IXOR, 'l', a.hi, b.hi); 1369 break; 1370 case TMUL: 1371 return funcmul128(f, l, r); 1372 case TDIV: 1373 return funcdiv128(f, t, l, r, 0); 1374 case TMOD: 1375 return funcdiv128(f, t, l, r, 1); 1376 case TLESS: 1377 case TGREATER: 1378 case TLEQ: 1379 case TGEQ: 1380 case TEQL: 1381 case TNEQ: { 1382 /* e->type here is plain int (a comparison's own result 1383 * type), not __int128, so this returns a scalar boolean 1384 * directly instead of falling through to the store128 at 1385 * the end of this case, which every arithmetic operator 1386 * above shares */ 1387 int issigned = t->u.arith.issigned; 1388 struct int128cmp c; 1389 struct value *res; 1390 switch (e->op) { 1391 case TLESS: 1392 res = cmp128(f, a, b, issigned).lt; 1393 break; 1394 case TGREATER: 1395 res = cmp128(f, b, a, issigned).lt; 1396 break; 1397 case TLEQ: 1398 c = cmp128(f, b, a, issigned); 1399 res = funcinst(f, IXOR, 'l', c.lt, mkintconst(1)); 1400 break; 1401 case TGEQ: 1402 c = cmp128(f, a, b, issigned); 1403 res = funcinst(f, IXOR, 'l', c.lt, mkintconst(1)); 1404 break; 1405 case TEQL: 1406 res = cmp128(f, a, b, issigned).eq; 1407 break; 1408 default: /* TNEQ */ 1409 c = cmp128(f, a, b, issigned); 1410 res = funcinst(f, IXOR, 'l', c.eq, mkintconst(1)); 1411 break; 1412 } 1413 return funcinst(f, ICNEL, 'w', res, mkintconst(0)); 1414 } 1415 default: 1416 error(&tok.loc, "this operator is not yet supported for __int128"); 1417 return NULL; 1418 } 1419 return store128(f, lo, hi); 1420 } 1421 if (t->kind == TYPECOMPLEX) { 1422 /* complex addition and subtraction are componentwise, no 1423 * carry propagation of any kind needed between the real and 1424 * imaginary parts (unlike __int128's words above). multiply 1425 * and divide use the ordinary cross-term formulas, real 1426 * scalar mul/add/sub qbe already has, no new runtime or 1427 * branching needed. == and != (the only orderings c defines 1428 * for a complex type) compare both components and return a 1429 * plain int, so those return early instead of falling 1430 * through to the storecomplex every arithmetic operator above 1431 * shares */ 1432 struct complexparts a, b; 1433 struct value *re, *im; 1434 struct qbetype qt; 1435 a = loadcomplex(f, t, l); 1436 b = loadcomplex(f, t, r); 1437 qt = qbetype(t->base); 1438 switch (e->op) { 1439 case TADD: 1440 re = funcinst(f, IADD, qt.base, a.re, b.re); 1441 im = funcinst(f, IADD, qt.base, a.im, b.im); 1442 break; 1443 case TSUB: 1444 re = funcinst(f, ISUB, qt.base, a.re, b.re); 1445 im = funcinst(f, ISUB, qt.base, a.im, b.im); 1446 break; 1447 case TMUL: 1448 /* (a.re+a.im*i)(b.re+b.im*i) = (a.re*b.re - a.im*b.im) + 1449 * (a.re*b.im + a.im*b.re)*i */ 1450 re = funcinst( 1451 f, 1452 ISUB, 1453 qt.base, 1454 funcinst(f, IMUL, qt.base, a.re, b.re), 1455 funcinst(f, IMUL, qt.base, a.im, b.im) 1456 ); 1457 im = funcinst( 1458 f, 1459 IADD, 1460 qt.base, 1461 funcinst(f, IMUL, qt.base, a.re, b.im), 1462 funcinst(f, IMUL, qt.base, a.im, b.re) 1463 ); 1464 break; 1465 case TDIV: { 1466 /* multiply num and denom by conj(b): denom becomes the 1467 * real scalar b.re^2+b.im^2, num becomes (a.re*b.re + 1468 * a.im*b.im) + (a.im*b.re - a.re*b.im)*i */ 1469 struct value *denom = funcinst( 1470 f, 1471 IADD, 1472 qt.base, 1473 funcinst(f, IMUL, qt.base, b.re, b.re), 1474 funcinst(f, IMUL, qt.base, b.im, b.im) 1475 ); 1476 struct value *numre = funcinst( 1477 f, 1478 IADD, 1479 qt.base, 1480 funcinst(f, IMUL, qt.base, a.re, b.re), 1481 funcinst(f, IMUL, qt.base, a.im, b.im) 1482 ); 1483 struct value *numim = funcinst( 1484 f, 1485 ISUB, 1486 qt.base, 1487 funcinst(f, IMUL, qt.base, a.im, b.re), 1488 funcinst(f, IMUL, qt.base, a.re, b.im) 1489 ); 1490 re = funcinst(f, IDIV, qt.base, numre, denom); 1491 im = funcinst(f, IDIV, qt.base, numim, denom); 1492 break; 1493 } 1494 case TEQL: 1495 case TNEQ: { 1496 enum instkind eqop = t->base->size == 4 ? ICEQS : ICEQD; 1497 struct value *req = funcinst(f, eqop, 'w', a.re, b.re); 1498 struct value *ieq = funcinst(f, eqop, 'w', a.im, b.im); 1499 struct value *both = funcinst(f, IAND, 'w', req, ieq); 1500 if (e->op == TNEQ) 1501 both = funcinst(f, IXOR, 'w', both, mkintconst(1)); 1502 return funcinst(f, ICNEW, 'w', both, mkintconst(0)); 1503 } 1504 default: 1505 error(&tok.loc, "this operator is not yet supported for complex types"); 1506 return NULL; 1507 } 1508 return storecomplex(f, t, re, im); 1509 } 1510 switch (e->op) { 1511 case TMUL: 1512 op = IMUL; 1513 break; 1514 case TDIV: 1515 op = !(t->prop & PROPINT) || t->u.arith.issigned ? IDIV : IUDIV; 1516 break; 1517 case TMOD: 1518 op = t->u.arith.issigned ? IREM : IUREM; 1519 break; 1520 case TADD: 1521 op = IADD; 1522 break; 1523 case TSUB: 1524 op = ISUB; 1525 break; 1526 case TSHL: 1527 op = ISHL; 1528 break; 1529 case TSHR: 1530 op = t->u.arith.issigned ? ISAR : ISHR; 1531 break; 1532 case TBOR: 1533 op = IOR; 1534 break; 1535 case TBAND: 1536 op = IAND; 1537 break; 1538 case TXOR: 1539 op = IXOR; 1540 break; 1541 case TLESS: 1542 if (t->size <= 4) 1543 op = t->prop & PROPFLOAT ? ICLTS : t->u.arith.issigned ? ICSLTW : ICULTW; 1544 else 1545 op = t->prop & PROPFLOAT ? ICLTD : t->u.arith.issigned ? ICSLTL : ICULTL; 1546 break; 1547 case TGREATER: 1548 if (t->size <= 4) 1549 op = t->prop & PROPFLOAT ? ICGTS : t->u.arith.issigned ? ICSGTW : ICUGTW; 1550 else 1551 op = t->prop & PROPFLOAT ? ICGTD : t->u.arith.issigned ? ICSGTL : ICUGTL; 1552 break; 1553 case TLEQ: 1554 if (t->size <= 4) 1555 op = t->prop & PROPFLOAT ? ICLES : t->u.arith.issigned ? ICSLEW : ICULEW; 1556 else 1557 op = t->prop & PROPFLOAT ? ICLED : t->u.arith.issigned ? ICSLEL : ICULEL; 1558 break; 1559 case TGEQ: 1560 if (t->size <= 4) 1561 op = t->prop & PROPFLOAT ? ICGES : t->u.arith.issigned ? ICSGEW : ICUGEW; 1562 else 1563 op = t->prop & PROPFLOAT ? ICGED : t->u.arith.issigned ? ICSGEL : ICUGEL; 1564 break; 1565 case TEQL: 1566 if (t->size <= 4) 1567 op = t->prop & PROPFLOAT ? ICEQS : ICEQW; 1568 else 1569 op = t->prop & PROPFLOAT ? ICEQD : ICEQL; 1570 break; 1571 case TNEQ: 1572 if (t->size <= 4) 1573 op = t->prop & PROPFLOAT ? ICNES : ICNEW; 1574 else 1575 op = t->prop & PROPFLOAT ? ICNED : ICNEL; 1576 break; 1577 default: 1578 break; 1579 } 1580 if (op == INONE) 1581 fatal( 1582 "internal error; unimplemented binary " 1583 "expression" 1584 ); 1585 v = funcinst(f, op, qbetype(e->type).base, l, r); 1586 if (t->kind == TYPEBITINT) 1587 v = funcbits(f, t, v, (struct bitfield){0}); 1588 return v; 1589 case EXPRCOND: 1590 b[0] = mkblock("cond_true"); 1591 b[1] = mkblock("cond_false"); 1592 b[2] = mkblock("cond_join"); 1593 1594 v = funcbranch(f, e->base, b[0], b[1]); 1595 1596 funclabel(f, b[0]); 1597 if (e->u.cond.t != e->base) 1598 v = funcexpr(f, e->u.cond.t); 1599 b[2]->phi.val[0] = convert(f, e->type, e->u.cond.t->type, v); 1600 b[2]->phi.blk[0] = f->end; 1601 funcjmp(f, b[2]); 1602 1603 funclabel(f, b[1]); 1604 v = funcexpr(f, e->u.cond.f); 1605 b[2]->phi.val[1] = convert(f, e->type, e->u.cond.f->type, v); 1606 b[2]->phi.blk[1] = f->end; 1607 1608 funclabel(f, b[2]); 1609 if (e->type == &typevoid) 1610 return NULL; 1611 functemp(f, &b[2]->phi.res); 1612 b[2]->phi.class = qbetype(e->type).base; 1613 return &b[2]->phi.res; 1614 case EXPRASSIGN: 1615 r = funcexpr(f, e->u.assign.r); 1616 if (e->u.assign.l->kind == EXPRTEMP) { 1617 e->u.assign.l->u.temp = r; 1618 } else { 1619 lval = funclval(f, e->u.assign.l); 1620 r = funcstore(f, e->u.assign.l->type, e->u.assign.l->qual, lval, r); 1621 } 1622 return r; 1623 case EXPRCOMMA: 1624 for (e = e->base; e->next; e = e->next) 1625 funcexpr(f, e); 1626 return funcexpr(f, e); 1627 case EXPRBUILTIN: 1628 switch (e->u.builtin.kind) { 1629 case BUILTINVASTART: 1630 l = funcexpr(f, e->base); 1631 funcinst(f, IVASTART, 0, l, NULL); 1632 break; 1633 case BUILTINVAARG: 1634 if (e->toeval) 1635 funcexpr(f, e->toeval); 1636 /* https:// todo.sr.ht/~mcf/cproc/52 */ 1637 if (!(e->type->prop & PROPSCALAR)) 1638 error( 1639 &tok.loc, 1640 "va_arg with non-scalar type " 1641 "is not yet supported" 1642 ); 1643 l = funcexpr(f, e->base); 1644 return funcinst(f, IVAARG, qbetype(e->type).base, l, NULL); 1645 case BUILTINALLOCA: 1646 l = funcexpr(f, e->base); 1647 return funcinst(f, IALLOC16, ptrclass, l, NULL); 1648 case BUILTINUNREACHABLE: 1649 funchlt(f); 1650 return NULL; 1651 case BUILTINATOMICLOAD: 1652 t = e->base->type->base; 1653 l = funcexpr(f, e->base); 1654 fn = mkatomicfn(t, "__atomic_load"); 1655 v = funcinst(f, ICALL, qbetype(t).base, fn, NULL); 1656 funcinst(f, IARG, ptrclass, l, NULL); 1657 return v; 1658 case BUILTINATOMICSTORE: 1659 t = e->base->type->base; 1660 l = funcexpr(f, e->base); 1661 r = funcexpr(f, e->u.builtin.val); 1662 fn = mkatomicfn(t, "__atomic_store"); 1663 funcinst(f, ICALL, 0, fn, NULL); 1664 funcinst(f, IARG, ptrclass, l, NULL); 1665 funcinst(f, IARG, qbetype(t).base, r, NULL); 1666 return NULL; 1667 case BUILTINATOMICEXCHANGE: 1668 t = e->base->type->base; 1669 l = funcexpr(f, e->base); 1670 r = funcexpr(f, e->u.builtin.val); 1671 fn = mkatomicfn(t, "__atomic_exchange"); 1672 v = funcinst(f, ICALL, qbetype(t).base, fn, NULL); 1673 funcinst(f, IARG, ptrclass, l, NULL); 1674 funcinst(f, IARG, qbetype(t).base, r, NULL); 1675 return v; 1676 case BUILTINATOMICCOMPAREEXCHANGE: 1677 t = e->base->type->base; 1678 l = funcexpr(f, e->base); 1679 v2 = funcexpr(f, e->u.builtin.val2); 1680 r = funcexpr(f, e->u.builtin.val); 1681 fn = mkatomicfn(t, "__atomic_compare_exchange"); 1682 v = funcinst(f, ICALL, qbetype(e->type).base, fn, NULL); 1683 funcinst(f, IARG, ptrclass, l, NULL); 1684 funcinst(f, IARG, ptrclass, v2, NULL); 1685 funcinst(f, IARG, qbetype(t).base, r, NULL); 1686 return v; 1687 case BUILTINATOMICFETCHADD: 1688 case BUILTINATOMICFETCHSUB: 1689 case BUILTINATOMICFETCHAND: 1690 case BUILTINATOMICFETCHOR: 1691 case BUILTINATOMICFETCHXOR: 1692 t = e->base->type->base; 1693 l = funcexpr(f, e->base); 1694 r = funcexpr(f, e->u.builtin.val); 1695 switch (e->u.builtin.kind) { 1696 case BUILTINATOMICFETCHADD: 1697 fn = mkatomicfn(t, "__atomic_fetch_add"); 1698 break; 1699 case BUILTINATOMICFETCHSUB: 1700 fn = mkatomicfn(t, "__atomic_fetch_sub"); 1701 break; 1702 case BUILTINATOMICFETCHAND: 1703 fn = mkatomicfn(t, "__atomic_fetch_and"); 1704 break; 1705 case BUILTINATOMICFETCHOR: 1706 fn = mkatomicfn(t, "__atomic_fetch_or"); 1707 break; 1708 default: 1709 fn = mkatomicfn(t, "__atomic_fetch_xor"); 1710 break; 1711 } 1712 v = funcinst(f, ICALL, qbetype(t).base, fn, NULL); 1713 funcinst(f, IARG, ptrclass, l, NULL); 1714 funcinst(f, IARG, qbetype(t).base, r, NULL); 1715 return v; 1716 default: 1717 fatal("internal error: unimplemented builtin"); 1718 } 1719 return NULL; 1720 case EXPRTEMP: 1721 assert(e->u.temp); 1722 return e->u.temp; 1723 case EXPRSIZEOF: 1724 t = e->u.szof.type; 1725 assert(t->kind == TYPEARRAY); 1726 calcvla(f, t); 1727 /* if the sizeof operand has VLA type, we must evaluate it */ 1728 if (e->base) 1729 funcexpr(f, e->base); 1730 return t->u.array.size; 1731 default: 1732 break; 1733 } 1734 fatal("unimplemented expression %d", e->kind); 1735 return NULL; 1736 } 1737 1738 static void 1739 zero( 1740 struct func *func, 1741 struct value *addr, 1742 int align, 1743 unsigned long long offset, 1744 unsigned long long end 1745 ) 1746 { 1747 static const enum instkind store[] = { 1748 [1] = ISTOREB, 1749 [2] = ISTOREH, 1750 [4] = ISTOREW, 1751 [8] = ISTOREL, 1752 }; 1753 static struct value z = {.kind = VALUE_INTCONST}; 1754 struct value *tmp; 1755 int a = 1; 1756 1757 while (offset < end) { 1758 if ((align - (offset & align - 1)) & a) { 1759 tmp = offset ? funcinst(func, IADD, ptrclass, addr, mkintconst(offset)) : addr; 1760 funcinst(func, store[a], 0, &z, tmp); 1761 offset += a; 1762 } 1763 if (a < align) 1764 a <<= 1; 1765 } 1766 } 1767 1768 void 1769 funcinit(struct func *func, struct decl *d, struct init *init, bool hasinit) 1770 { 1771 struct lvalue dst; 1772 struct value *src, *v; 1773 unsigned long long offset = 0, max = 0; 1774 size_t i, w; 1775 1776 funcalloc(func, d); 1777 if (!hasinit) 1778 return; 1779 for (; init; init = init->next) { 1780 zero(func, d->value, d->type->align, offset, init->start); 1781 dst.bits = init->bits; 1782 if (init->expr->kind == EXPRSTRING) { 1783 w = init->expr->type->base->size; 1784 for (i = 0; i < init->expr->u.string.size && i * w < init->end - init->start; ++i) { 1785 v = mkintconst(init->start + i * w); 1786 dst.addr = funcinst(func, IADD, ptrclass, d->value, v); 1787 switch (w) { 1788 case 1: 1789 v = mkintconst(((unsigned char *)init->expr->u.string.data)[i]); 1790 break; 1791 case 2: 1792 v = mkintconst(((uint_least16_t *)init->expr->u.string.data)[i]); 1793 break; 1794 case 4: 1795 v = mkintconst(((uint_least32_t *)init->expr->u.string.data)[i]); 1796 break; 1797 } 1798 funcstore(func, init->expr->type->base, QUALNONE, dst, v); 1799 } 1800 offset = init->start + i * w; 1801 } else { 1802 if (offset < init->end && (dst.bits.before || dst.bits.after)) 1803 zero(func, d->value, d->type->align, offset, init->end); 1804 dst.addr = d->value; 1805 /* 1806 * qbe's memopt does not eliminate the store for ptr + 0, 1807 * so only emit the add if the offset is non-zero 1808 */ 1809 if (init->start > 0) 1810 dst.addr = funcinst(func, IADD, ptrclass, dst.addr, mkintconst(init->start)); 1811 src = funcexpr(func, init->expr); 1812 funcstore(func, init->expr->type, QUALNONE, dst, src); 1813 offset = init->end; 1814 } 1815 if (max < offset) 1816 max = offset; 1817 } 1818 zero(func, d->value, d->type->align, max, d->type->size); 1819 } 1820 1821 static void 1822 casesearch( 1823 struct func *f, 1824 int class, 1825 struct value *v, 1826 struct switchcase *c, 1827 struct block *defaultlabel, 1828 unsigned long long min, 1829 unsigned long long max 1830 ) 1831 { 1832 struct value *res, *key; 1833 struct block *label[3]; 1834 1835 if (!c) { 1836 funcjmp(f, defaultlabel); 1837 return; 1838 } 1839 if (min == max) { 1840 funcjmp(f, c->body); 1841 return; 1842 } 1843 label[0] = mkblock("switch_ne"); 1844 label[1] = mkblock("switch_lt"); 1845 label[2] = mkblock("switch_gt"); 1846 1847 key = mkintconst(c->node.key); 1848 res = funcinst(f, class == 'w' ? ICEQW : ICEQL, 'w', v, key); 1849 funcjnz(f, res, NULL, c->body, label[0]); 1850 funclabel(f, label[0]); 1851 res = funcinst(f, class == 'w' ? ICULTW : ICULTL, 'w', v, key); 1852 funcjnz(f, res, NULL, label[1], label[2]); 1853 funclabel(f, label[1]); 1854 casesearch(f, class, v, c->node.child[0], defaultlabel, min, c->node.key - 1); 1855 funclabel(f, label[2]); 1856 casesearch(f, class, v, c->node.child[1], defaultlabel, c->node.key + 1, max); 1857 } 1858 1859 void 1860 funcswitch(struct func *f, struct value *v, struct switchcases *c, struct block *defaultlabel) 1861 { 1862 casesearch(f, qbetype(c->type).base, v, c->root, defaultlabel, 0, -1); 1863 } 1864 1865 /* emit */ 1866 1867 static void 1868 emitname(struct value *v) 1869 { 1870 static const char sigil[] = { 1871 [VALUE_TEMP] = '%', 1872 [VALUE_GLOBAL] = '$', 1873 [VALUE_TYPE] = ':', 1874 [VALUE_LABEL] = '@', 1875 }; 1876 int kind; 1877 1878 kind = v->kind & 0xf; 1879 if ((size_t)kind >= countof(sigil) || !sigil[kind]) 1880 fatal("invalid value"); 1881 putchar(sigil[kind]); 1882 if (kind == VALUE_GLOBAL && v->id) 1883 fputs(".L", stdout); 1884 if (v->kind & VALUE_QUOTE) 1885 putchar('"'); 1886 if (v->u.name) 1887 fputs(v->u.name, stdout); 1888 if (v->kind & VALUE_QUOTE) 1889 putchar('"'); 1890 if (v->id) 1891 printf(".%u", v->id); 1892 } 1893 1894 static void 1895 emitvalue(struct value *v) 1896 { 1897 switch (v->kind & 0xf) { 1898 case VALUE_INTCONST: 1899 printf("%llu", v->u.i); 1900 break; 1901 case VALUE_FLTCONST: 1902 printf("s_%.17g", v->u.f); 1903 break; 1904 case VALUE_DBLCONST: 1905 printf("d_%.17g", v->u.f); 1906 break; 1907 case VALUE_GLOBAL: 1908 if (v->kind & VALUE_EXTERN) 1909 fputs("extern ", stdout); 1910 if (v->kind & VALUE_THREAD) 1911 fputs("thread ", stdout); 1912 /* fallthrough */ 1913 default: 1914 emitname(v); 1915 break; 1916 } 1917 } 1918 1919 static void 1920 emitclass(int class, struct value *v) 1921 { 1922 if (v && v->kind == VALUE_TYPE) 1923 emitname(v); 1924 else if (class) 1925 putchar(class); 1926 else 1927 fatal("type has no QBE representation"); 1928 } 1929 1930 static unsigned emittypeid; 1931 1932 /* declares a synthetic two-word aggregate type for a value this 1933 * compiler represents as memory (an address) but qbe has no native 1934 * type for, __int128 (two 'l' words) and complex (two 's' or 'd' 1935 * words) so far. once qbe sees the declaration, its own aggregate-type 1936 * abi lowering classifies parameters and return values per the real 1937 * system v abi (register pair or stack/memory as the fields dictate) 1938 * exactly the way it already does for a real two-word struct, so 1939 * neither caller needs any abi classification code of its own */ 1940 static void 1941 emitpairtype(struct type *t, const char *name, char class) 1942 { 1943 t->value = xmalloc(sizeof(*t->value)); 1944 t->value->kind = VALUE_TYPE; 1945 t->value->u.name = name; 1946 t->value->id = ++emittypeid; 1947 fputs("type ", stdout); 1948 emitname(t->value); 1949 printf(" = { %c, %c }\n", class, class); 1950 } 1951 1952 /* XXX: need to consider _alignas on struct members */ 1953 static void 1954 emittype(struct type *t) 1955 { 1956 struct member *m, *other; 1957 struct type *sub; 1958 unsigned long long off; 1959 1960 if (t->value 1961 || (t->kind != TYPESTRUCT && t->kind != TYPEUNION && t->kind != TYPEINT128 1962 && t->kind != TYPECOMPLEX)) 1963 return; 1964 if (t->kind == TYPEINT128) { 1965 emitpairtype(t, t->u.arith.issigned ? "i128" : "u128", 'l'); 1966 return; 1967 } 1968 if (t->kind == TYPECOMPLEX) { 1969 emitpairtype(t, t->base == &typefloat ? "cfloat" : "cdouble", qbetype(t->base).base); 1970 return; 1971 } 1972 t->value = xmalloc(sizeof(*t->value)); 1973 t->value->kind = VALUE_TYPE; 1974 t->value->u.name = t->u.structunion.tag; 1975 t->value->id = ++emittypeid; 1976 for (m = t->u.structunion.members; m; m = m->next) { 1977 for (sub = m->type; sub->kind == TYPEARRAY; sub = sub->base) 1978 ; 1979 emittype(sub); 1980 } 1981 fputs("type ", stdout); 1982 emitname(t->value); 1983 if (t == targ->typevalist) { 1984 printf(" = align %d { %llu }\n", t->align, t->size); 1985 return; 1986 } 1987 fputs(" = { ", stdout); 1988 for (m = t->u.structunion.members, off = 0; m;) { 1989 if (t->kind == TYPESTRUCT) { 1990 /* look for a subsequent member with a larger storage 1991 * unit */ 1992 for (other = m->next; other; other = other->next) { 1993 if (other->offset >= ALIGNUP(m->offset + 1, 8)) 1994 break; 1995 if (other->offset <= m->offset) 1996 m = other; 1997 } 1998 off = m->offset + m->type->size; 1999 } else { 2000 fputs("{ ", stdout); 2001 } 2002 for (sub = m->type; sub->kind == TYPEARRAY; sub = sub->base) 2003 ; 2004 emitclass(qbetype(sub).data, sub->value); 2005 if (m->type->size > sub->size) 2006 printf(" %llu", m->type->size / sub->size); 2007 if (t->kind == TYPESTRUCT) { 2008 fputs(", ", stdout); 2009 /* skip subsequent members contained within the same 2010 * storage unit */ 2011 do 2012 m = m->next; 2013 while (m && m->offset < off); 2014 } else { 2015 fputs(" } ", stdout); 2016 m = m->next; 2017 } 2018 } 2019 puts("}"); 2020 } 2021 2022 static struct inst ** 2023 emitinst(struct inst **instp, struct inst **instend) 2024 { 2025 int op, first; 2026 struct inst *inst = *instp; 2027 2028 putchar('\t'); 2029 assert(inst->kind < countof(instname)); 2030 if (inst->res.kind) { 2031 emitvalue(&inst->res); 2032 fputs(" =", stdout); 2033 emitclass(inst->class, inst->arg[1]); 2034 putchar(' '); 2035 } 2036 fputs(instname[inst->kind], stdout); 2037 putchar(' '); 2038 emitvalue(inst->arg[0]); 2039 ++instp; 2040 op = inst->kind; 2041 switch (op) { 2042 case ICALL: 2043 putchar('('); 2044 for (first = 1; instp != instend; ++instp) { 2045 inst = *instp; 2046 if (inst->kind == IVARARG) { 2047 fputs(", ...", stdout); 2048 continue; 2049 } 2050 if (inst->kind != IARG) 2051 break; 2052 if (first) 2053 first = 0; 2054 else 2055 fputs(", ", stdout); 2056 emitclass(inst->class, inst->arg[1]); 2057 putchar(' '); 2058 emitvalue(inst->arg[0]); 2059 } 2060 putchar(')'); 2061 break; 2062 default: 2063 if (inst->arg[1]) { 2064 fputs(", ", stdout); 2065 emitvalue(inst->arg[1]); 2066 } 2067 } 2068 putchar('\n'); 2069 return instp; 2070 } 2071 2072 static void 2073 emitjump(struct jump *j) 2074 { 2075 switch (j->kind) { 2076 case JUMP_NONE: 2077 break; 2078 case JUMP_RET: 2079 fputs("\tret", stdout); 2080 if (j->arg) { 2081 fputc(' ', stdout); 2082 emitvalue(j->arg); 2083 } 2084 putchar('\n'); 2085 break; 2086 case JUMP_JMP: 2087 fputs("\tjmp ", stdout); 2088 emitname(&j->blk[0]->label); 2089 putchar('\n'); 2090 break; 2091 case JUMP_JNZ: 2092 fputs("\tjnz ", stdout); 2093 emitvalue(j->arg); 2094 fputs(", ", stdout); 2095 emitname(&j->blk[0]->label); 2096 fputs(", ", stdout); 2097 emitname(&j->blk[1]->label); 2098 putchar('\n'); 2099 break; 2100 case JUMP_HLT: 2101 fputs("\thlt\n", stdout); 2102 break; 2103 default: 2104 assert(0); 2105 } 2106 } 2107 2108 void 2109 emitfunc(struct func *f, bool global) 2110 { 2111 struct block *b; 2112 struct inst **inst, **instend; 2113 struct decl *p; 2114 struct value *v; 2115 2116 if (f->end->jump.kind == JUMP_NONE) { 2117 v = NULL; 2118 /* implicitly return 0 from main if we reach the end of the 2119 * function */ 2120 if (strcmp(f->name, "main") == 0 && f->type->base == &typeint) 2121 v = mkintconst(0); 2122 funcret(f, v); 2123 } 2124 if (global) 2125 puts("export"); 2126 fputs("function ", stdout); 2127 if (f->type->base != &typevoid) { 2128 emitclass(qbetype(f->type->base).base, f->type->base->value); 2129 putchar(' '); 2130 } 2131 emitname(f->decl->value); 2132 putchar('('); 2133 for (p = f->type->u.func.params, v = f->paramtemps; p; p = p->next, ++v) { 2134 if (p != f->type->u.func.params) 2135 fputs(", ", stdout); 2136 emitclass(qbetype(p->type).base, p->type->value); 2137 putchar(' '); 2138 emitname(v); 2139 } 2140 if (f->type->u.func.isvararg) { 2141 if (f->type->u.func.params) 2142 fputs(", ", stdout); 2143 fputs("...", stdout); 2144 } 2145 puts(") {"); 2146 for (b = f->start; b; b = b->next) { 2147 emitname(&b->label); 2148 putchar('\n'); 2149 if (b->phi.res.kind) { 2150 putchar('\t'); 2151 emitvalue(&b->phi.res); 2152 printf(" =%c phi ", b->phi.class); 2153 emitname(&b->phi.blk[0]->label); 2154 putchar(' '); 2155 emitvalue(b->phi.val[0]); 2156 fputs(", ", stdout); 2157 emitname(&b->phi.blk[1]->label); 2158 putchar(' '); 2159 emitvalue(b->phi.val[1]); 2160 putchar('\n'); 2161 } 2162 instend = (struct inst **)((char *)b->insts.val + b->insts.len); 2163 for (inst = b->insts.val; inst != instend;) 2164 inst = emitinst(inst, instend); 2165 emitjump(&b->jump); 2166 } 2167 puts("}"); 2168 } 2169 2170 static void 2171 dataitem(struct expr *expr, unsigned long long size) 2172 { 2173 struct decl *decl; 2174 size_t i, w; 2175 unsigned c; 2176 2177 switch (expr->kind) { 2178 case EXPRUNARY: 2179 if (expr->op != TBAND) 2180 fatal("not a address expr"); 2181 expr = expr->base; 2182 if (expr->kind != EXPRIDENT) 2183 error(&tok.loc, "initializer is not a constant expression"); 2184 decl = expr->u.ident.decl; 2185 if (decl->kind == DECLOBJECT && decl->u.obj.storage != SDSTATIC) 2186 error(&tok.loc, "initializer is not a constant expression"); 2187 emitname(decl->value); 2188 break; 2189 case EXPRBINARY: 2190 if (expr->op != TADD || expr->u.binary.l->kind != EXPRUNARY 2191 || expr->u.binary.r->kind != EXPRCONST) 2192 error(&tok.loc, "initializer is not a constant expression"); 2193 dataitem(expr->u.binary.l, 0); 2194 fputs(" + ", stdout); 2195 dataitem(expr->u.binary.r, 0); 2196 break; 2197 case EXPRCONST: 2198 if (expr->type->prop & PROPFLOAT) 2199 printf("%c_%.17g", expr->type->size == 4 ? 's' : 'd', expr->u.constant.f); 2200 else 2201 printf("%llu", expr->u.constant.u); 2202 break; 2203 case EXPRSTRING: 2204 w = expr->type->base->size; 2205 if (w == 1) { 2206 fputc('"', stdout); 2207 for (i = 0; i < expr->u.string.size && i < size; ++i) { 2208 c = ((unsigned char *)expr->u.string.data)[i]; 2209 if (isprint(c) && c != '"' && c != '\\') 2210 putchar(c); 2211 else 2212 printf("\\%03o", c); 2213 } 2214 fputc('"', stdout); 2215 } else { 2216 for (i = 0; i < expr->u.string.size && i * w < size; ++i) { 2217 switch (w) { 2218 case 2: 2219 printf("%" PRIuLEAST16 " ", ((uint_least16_t *)expr->u.string.data)[i]); 2220 break; 2221 case 4: 2222 printf("%" PRIuLEAST32 " ", ((uint_least32_t *)expr->u.string.data)[i]); 2223 break; 2224 default: 2225 assert(0); 2226 } 2227 } 2228 } 2229 if (i * w < size) 2230 printf(", z %llu", size - (unsigned long long)i * w); 2231 break; 2232 default: 2233 error(&tok.loc, "initializer is not a constant expression"); 2234 } 2235 } 2236 2237 void 2238 emitdata(struct decl *d, struct init *init) 2239 { 2240 struct init *cur; 2241 struct type *t; 2242 unsigned long long offset = 0, start, end, bits = 0; 2243 size_t i; 2244 int align; 2245 2246 align = d->u.obj.align; 2247 for (cur = init; cur; cur = cur->next) 2248 cur->expr = eval(cur->expr); 2249 if (d->u.obj.storage == SDTHREAD) 2250 fputs("thread ", stdout); 2251 if (d->linkage == LINKEXTERN) 2252 fputs("export ", stdout); 2253 fputs("data ", stdout); 2254 emitname(d->value); 2255 printf(" = align %d { ", align); 2256 2257 while (init) { 2258 cur = init; 2259 while ((init = init->next) 2260 && init->start * 8 + init->bits.before < cur->end * 8 - cur->bits.after) { 2261 /* 2262 * XXX: currently, if multiple union members are 2263 * initialized, these assertions may not hold 2264 (https:// todo.sr.ht/~mcf/cproc/38) 2265 */ 2266 assert(cur->expr->kind == EXPRSTRING); 2267 assert(init->expr->kind == EXPRCONST); 2268 i = (init->start - cur->start) / cur->expr->type->base->size; 2269 switch (cur->expr->type->base->size) { 2270 case 1: 2271 ((unsigned char *)cur->expr->u.string.data)[i] = init->expr->u.constant.u; 2272 break; 2273 case 2: 2274 ((uint_least16_t *)cur->expr->u.string.data)[i] = init->expr->u.constant.u; 2275 break; 2276 case 4: 2277 ((uint_least32_t *)cur->expr->u.string.data)[i] = init->expr->u.constant.u; 2278 break; 2279 } 2280 } 2281 start = cur->start + cur->bits.before / 8; 2282 end = cur->end - (cur->bits.after + 7) / 8; 2283 if (offset < start && bits) { 2284 printf("b %u, ", (unsigned)bits); /* unfinished byte from previous 2285 * bit-field */ 2286 ++offset; 2287 bits = 0; 2288 } 2289 if (offset < start) 2290 printf("z %llu, ", start - offset); 2291 if (cur->bits.before || cur->bits.after) { 2292 /* little-endian target specific */ 2293 assert(cur->expr->type->prop & PROPINT); 2294 assert(cur->expr->kind == EXPRCONST); 2295 bits |= cur->expr->u.constant.u << cur->bits.before % 8; 2296 for (offset = start; offset < end; ++offset, bits >>= 8) 2297 printf("b %u, ", (unsigned)bits & 0xff); 2298 /* 2299 * clear the upper `after` bits in the last byte, 2300 * or all bits when `after` is 0 (we ended on a 2301 * byte boundary) 2302 */ 2303 bits &= 0x7f >> (cur->bits.after + 7) % 8; 2304 } else { 2305 t = cur->expr->type; 2306 if (t->kind == TYPEARRAY) 2307 t = t->base; 2308 printf("%c ", qbetype(t).data); 2309 dataitem(cur->expr, cur->end - cur->start); 2310 fputs(", ", stdout); 2311 } 2312 offset = end; 2313 } 2314 if (bits) { 2315 printf("b %u, ", (unsigned)bits); 2316 ++offset; 2317 } 2318 assert(offset <= d->type->size); 2319 if (offset < d->type->size) 2320 printf("z %llu ", d->type->size - offset); 2321 puts("}"); 2322 }