2014年6月22日 星期日

LLVM tablegen multiclass definitions and instances


tablegen 的目的是為了提出records 中,所共有的部分。
所以許多語言特色都是用來簡化,

例如: class template arguments

以下面這個例子來說
def bork {      // Value
  bit isMod = 1;
  bit isRef = 0;
}
def hork {      // Value
  bit isMod = 1;
  bit isRef = 1;
}
def zork {      // Value
  bit isMod = 0;
  bit isRef = 1;
}



可以改寫成


class ModRefValue< bit<2>  value >{
bit<2> Value = value
}

class Value<ModRefValue MR> {
bit isMod = MR.Value{0}
bit isRef = MR.Value{0}
}

def bork : Value<Mod>
def hork : Value<ModRef>
def zork : Value<Ref>


看起來簡化多了。
class template arguments 是用來簡化class 內部的value
接下來介紹multiclass definition and instances
可以用來簡化class instance


def ADD_rr : rrinst<0b111, "add">;
def ADD_ri : riinst<0b111, "add">;
def SUB_rr : rrinst<0b101, "sub">;
def SUB_ri : riinst<0b101, "sub">;
def MUL_rr : rrinst<0b100, "mul">;
def MUL_ri : riinst<0b100, "mul">;


很多指令都有_rr, _ri 這兩種版本,
能不能再class instantiation 的時候只宣告一次add, sub, mul 就好
能可以自動定義出add_rr, add_ri 這兩種版本,
這時候就要用multiclass 跟defm

defm ADD : ri_insn<0b111, "add">
defm SUB : ri_insn<0b101, "sub">
defm MUL : ri_insn<0b100, "mul">

multiclass ri_insn < > {

def _rr
def _ri

}
(產生出來的def 會做string concatenation)

而且defm 不只可以放在外面,也可以放在multiclass裡面
參考 http://llvm.org/docs/TableGen/LangIntro.html


2014年6月17日 星期二

用python 來取代shell script


最近工作上,原本有個程式是用shell script 寫的,目的也就是一些簡單的整合應用
但後來越寫越大, 覺得程式碼好醜( shell language 真是我看過最醜的語言)
索性把整個shell script 改寫成python

原本就預期改寫之後的程式碼會比較清晰 而且更短
結果果然是這樣, 驗證了python 真的能夠快速開發的設計理念

但人還是不滿足
python 最強大的library 也成了最大的問題
這麼多module, function name, 怎麼記得住阿?

救星很可能就是ipython (http://ipython.org/index.html)

2014年6月12日 星期四

Preprocessor # and ##

 

介紹兩個用在macro 的運算子

## : 把macro 裡的參數,跟其他string 串接起來

# : 把macro 裡的參數,當作string

#define w(n) "imm"#n
#define w2(n) imm##n

int main()
{
  int imm5 = 10;
  printf("%s\n", w(10));
  printf("%d\n", w2(5));
  return 0;
}

第一個printf 我想要一個string 當參數 所以用#

第二個printf 我想要一個變數 所以用##

 

Reference

https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html

2014年6月11日 星期三

Build LLVM with cmake

 

cmake 可以產生不同的build file (ex: unix makefile)

cmake –help
最後面會列出在你平台環境上可以產生的makefile 種類

cmake –G “Unix Makefiles”
指令產生"Unix Makefiles”
如果不指定,也會自動偵測。

所以build LLVM 最簡單的命令就是在build directory

cmake PATH/TO/LLVM/SRC
make

 

其它variable 請參考
http://llvm.org/docs/CMake.html#options-and-variables

cmake -DLLVM_TARGETS_TO_BUILD="X86”     # only build x86 target
           -DCMAKE_INSTALL_PREFIX="$PWD/../install"   # specify installation path
           ../llvm-3.4.1.src/   

Newlib syscall


在porting Newlib for a new architecture 要注意事項,第六點
  1. Add a platform subdirectory to libgloss You need to add a bsp for your platform. This is the minimum set of syscalls needed by newlib and any linker scripts needed. This varies from board to board (it can also be a simulator). See the mn10300 or fr30 for examples. You will need to edit configure.in and regenerate configure so it will build your new files. By default you get libnosys which gives you a set of default syscall stubs. The majority of the stubs just return failure. You still need to supply an __exit routine. This can be as simple as generating an exception to stop the program.
意思是說要在libgross 下新增一個architecture directory
並且實作必要提供的最少syscall
以read system call 來說,_read_r 會需要底層平台支援(呼叫_read),
所以必須提供所謂BSP 也就是libgross,內含處理這些system call的實作。
reent/readr.c
_ssize_t
_DEFUN (_read_r, (ptr, fd, buf, cnt),
     struct _reent *ptr _AND
     int fd _AND
     _PTR buf _AND
     size_t cnt)
{
  _ssize_t ret;
  errno = 0;
  if ((ret = (_ssize_t)_read (fd, buf, cnt)) == -1 && errno != 0)
    ptr->_errno = errno;
  return ret;
}
libgloss/fr30/syscalls.c
int
_read (file, ptr, len)
     int    file;
     char * ptr;
     int    len;
{
  asm ("ldi:8 %0, r0" :: "i" (SYS_read) : "r0");
  asm ("int   #10");
  return;
}

僅是發system call,讓Vector Table 內的system call handler 去處理。



2014年6月10日 星期二

Newlib reentrancy


引用Newlib 的原文
Reentrancy is a characteristic of library functions which allows multiple processes to use the same address space with assurance that the values stored in those spaces will remain constant between calls.
意思是說,當某process A 執行function到一半的時候, 允許其他processes B 去執行,並且可以確保B執行完畢之後,A 還可以正確的執行剩下的指令。
一開始我對這個reentrancy 的定義很confused,原因是我記得reentrancy 跟thread-safe 是兩件事,可參考 Wiki Reentrancy ,reentrancy 是在談single process 環境下,user code 與ISR的關係 (這並不是multithread)。
但Newlib 很顯然是把reentrancy 跟multithreading  扯在一起了。為了繼續看下去,只好先接受它的定義囉。
為什麼library function 要reentrant ?
最簡單的例子是errno
每個thread 都應該維護自己的errno,不可以影響其他thread 的執行。

所以Newlib 維護了一個reentrancy structure  struct _reent,內含所有會被library 修改到的global variables。errno 當然是其中一個member,而且還是第一個。(因為它太常被修改到了)
而user 使用到的errno 其實並不是變數,而是macro
這個macro 會替換成_reent 內的errno。

再繼續看下去之前,先談談
其實Newlib 也提供不需要reentrancy 的版本。
而這些版本的code 只要共同存取一個global reentrancy structure 就好了
(根本就不需要reentrant 了,還要去集中管理,這設計很奇怪)
newlib/libc/include/sys/errno.h
#ifndef _REENT_ONLY
#define errno (*__errno())
extern int *__errno _PARAMS ((void));
#endif

newlib/libc/errno/errno.c
int *
__errno ()
{
  return &_REENT->_errno;
}
newlib/libc/include/sys/reent.h
#if defined(__DYNAMIC_REENT__) && !defined(__SINGLE_THREAD__)
#ifndef __getreent
  struct _reent * _EXFUN(__getreent, (void));
#endif
# define _REENT (__getreent())
#else /* __SINGLE_THREAD__ || !__DYNAMIC_REENT__ */
# define _REENT _impure_ptr#endif /* __SINGLE_THREAD__ || !__DYNAMIC_REENT__ */
newlib/libc/reent/impure.c
static struct _reent __ATTRIBUTE_IMPURE_DATA__ impure_data = _REENT_INIT (impure_data);
struct _reent *__ATTRIBUTE_IMPURE_PTR__ _impure_ptr = &impure_data;
所以得到 _REENT 是指到global reentrancy structure 的指標。
(不需要reentrancy 的code 都可以使用_REENT)
但NEWLIB 同時也提供了要reentrant 的版本
通常這些function 都是prependding ‘_’ 跟pendding ‘_r"’
例如: fopen

FILE *
_DEFUN(_fopen_r, (ptr, file, mode),
       struct _reent *ptr _AND
       _CONST char *__restrict file _AND
       _CONST char *__restrict mode)
{
…
}
#ifndef _REENT_ONLY
FILE *
_DEFUN(fopen, (file, mode),
       _CONST char *file _AND
       _CONST char *mode)
{
  return _fopen_r (_REENT, file, mode);
}
#endif

fopen 是non-reentrant 的版本 ,所以它使用global _REENT
_fopen_r 是reentrant 的版本,ptr是用來接收自己的unique _reent
所以如果_fopen_r 要設定errno,只要使用ptr->_errno 就可以改到自己的unique _reent 囉








gcc preprocessor build-in macros

 
GCC preprocessor 定義了許多macro 可以用來幫助程式員,
要怎樣看看這些macro ?
echo "" | cpp -E –dM
這邊舉幾個例子來看看這些macro 可以幫助我們什麼?
1. 想知道你的機器是X86_64 還是I386 ?
#include <stdio.h>
int main() {
#if defined(__x86_64__)
        printf("hello x86_64\n");
#elif defined(__i386__)
        printf("hello i386\n");
#endif
  return 0;
}
2. 想知道你機器上的integer pointer  type 是定義成什麼?
在x86_64
~/tmp $ echo "" | cpp -E -dM | grep __INTPTR_TYPE__
#define __INTPTR_TYPE__ long int
在i386
~/tmp $ echo "" | cpp -E -dM | grep __INTPTR_TYPE__
#define __INTPTR_TYPE__ int










composite data type – its alignment and size


* array

alignment - 等同於元素的alignment
size - 元素size * 元素個數
example:
int array[10];
alignment – 4bytes
size – 4 * 10 bytes

* aggregate (struct)

alignment - 元素中最大的alignment
size – alignment 的最小倍數,並且足以容納所有元素
example:
struct {
char c;
int i;
};
alignment – 4 bytes
size – 8 bytes

* union

alignment - 元素中最大的alignment
size – alignment 的最小倍數,並且足以容納最大size的元素。
union {
char c;
int i;
};
alignment – 4 bytes;
size -  4 bytes

packed variable attribute

#include <stdio.h>
struct data {
        int i;
        char c[3];
        int i2;
}mydata;
struct data1 {
        int i;
        char c[3];
        int i2;
} __attribute__((packed)) mydata1;
enum number {
        n1,
        n2,
        n3,
} number;
enum number1 {
        n11,
        n12,
        n13,
} __attribute__((packed)) number1;
 
int main()
{
  printf ("size of mydata is %lu\n", sizeof (mydata));
  printf ("%p\n", &mydata.i);
  printf ("%p\n", &mydata.c);
  printf ("%p\n", &mydata.i2);
  printf ("size of mydata1 is %lu\n", sizeof (mydata1));
  printf ("%p\n", &mydata1.i);
  printf ("%p\n", &mydata1.c);
  printf ("%p\n", &mydata1.i2);
  printf ("size of number is %lu\n", sizeof (number));
  printf ("size of number1 is %lu\n", sizeof (number1));
  return 0;
}
===================================
size of mydata is 12
300df4
300df8
300dfc
size of mydata1 is 11
300de8
300dec
300def
size of number is 4
size of number1 is 1

====================================
packed 這個variable attribute 可以套用在struct、union、enum。
目的是讓這些結構使用最少的記憶體,
例如:
mydata, compiler 為了performance 通常會對齊資料,所以i2 被強制對齊到4bytes align (儘管c 只用了3byte)
但加了packed 的mydata1,就不管i2 要4bytes align的要求了。
同樣地,用到enum, 會用最小的integral type 來做enumation。
原本是用int (4bytes),改成最小的byte了









2014年6月8日 星期日

human-like robot called Pepper

http://www.taiwannews.com.tw/etn/news_content.php?id=2498393


Guo said that he was honor to be part of such a momentous initiative.

momentous 重要的
initiative 首創精神

The initiative of the work was done by our chief engineer.


http://www.bbc.com/news/technology-27709828

The overall estimate is worth about XXX.

The next big thing



http://www.taiwannews.com.tw/etn/news_content.php?id=2499767


Computex, Taipei 2014, is the second largest computer trade show.
This year, it drew a record number of international buyers and visitors, that's one percent more than the last year's show did according the International External Trade Council.  (國際外貿協會). Of 166 countries and regions, the strongest ones are from China and US.

The executive vice president mark this the end of the show at a press conference.



during its five-day run.
-> during its five-day period. 
run 有經營的意思
A well-run company 經營良好的公司

The largest increase was seen among XXX, OOO, and ZZZ with XXX percent, OOO percent, and ZZZ percent respectively.

The number of China buyers also showed strong annual growth of XX percent,
making China the largest single source of buyers at this year's computex.

The trade show is expected to have generated over US$25 billion in business
-> The trade show is expected to generate over US$25 billion in business.
the same as the exhibition in 2013
-> as much as the exhibition in 2013
representing 22 percent of Taiwan's annual amount in Information and Communication technology export. 

The amount of trade in 34th computex represents 22 percent of Taiwan's annual amount of export in Information and Communication. 

He is quite confident after seeing these good result, attributing the good result to economic recovery in US. and Europe.
attribute 把...歸咎(因)於
I attribute my good performance to my strict discipline. 
我的表現歸因於嚴格的紀律
It's improper to attribute the failure to others. 
把失敗歸因於別人

attribute 認為是某人所有
to attribute the weakness to women. 
把軟弱認為是女人所應有的

wearable devices and Internet of thing (IOT) is the trend of future technology,
Can I find out the future start from stock market? 

2014年6月4日 星期三

GCC – always_inline attribute


下面這個例子,gcc 會warning
hello.c: In function 'api':
hello.c:4:5: warning: asm operand 0 probably doesn't match constraints [enabled by default]
     __asm__ ("add\t%0"
     ^
hello.c:4:5: error: impossible constraint in 'asm'


static inline void api (const unsigned data)
{
    __asm__ ("add\t%0"
            :
            : "i" (data)
            );
}
int main()
{
  const unsigned i = 10;
  api(1);
  return 0;
}

錯誤的原因是 api 內要求data 必須是integer “I”
但是data 一定是常數? 它也有可能是變數,就像main 中傳了i 給api
所以就有可能不滿足限制。
那把api(i) 改成 api(10); 可以嗎?
還是不行 因為其他user 還是可以用api(i)這種寫法
解決方法:
1. 讓gcc 做優化
gcc –O1
這樣 const unsigned data 就真的會變成 integer 而不是變數
2. always_inline

always_inline
Generally, functions are not inlined unless optimization is specified. For functions declared inline, this attribute inlines the function even if no optimization level is specified. inline function 原本只是建議,但加了always_inline 即使是在O0 的情況下,
這個function 還是會被inline 到main 去,所以const unsigned data 會被拿掉,
直接用1 取代data。
但這樣做怪怪的,如果把程式換成
int main()
{
  const unsigned i = 10;
  api(i);   // 用variable i
  return 0;
}
always_inline 也不行了
為什麼? 看起來是在O0 情況下,並沒有辦法把i 取代成10

下面 網頁列出 –O –O1 情況下,有打開的optimization,可以試試看到底是那些optimizations 才可以。

https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html

GCC – function/variable attribute

 

Reference:

Declaring Attributes of Functions

 

Specifying Attributes of Variables

2014年6月2日 星期一

Choose the right industry while you are looking for a job.


Taipei COMPUTEX: 'A good indication' of tech outlook, says Barclays

http://www.taiwannews.com.tw/etn/news_content.php?id=2495539


------------------------------------------------------------------------------------------------------------------------------
This article talks about the computex exhibition 2014.
Two major PC maker ASUS and ACER will show their latest product, including wearable product and new low-cost smartphone.
ASUS will unveil their new transformer tablet with low cost, from the view of a customer, I won't expect their product too much, because the market of smartphone and tablet is becoming more and more competitive and low benefit.
As for ACER, it will exhibit his first wearable watch which can receive text message and be used to monitor user's heart rate.
In my opinion, this product is not an innovation, because Samsung has showed many kind of similar product to market.
The wearable product is a trend, but is still looking for the new application.
(I don't think I would pay for this new watch, but I would like to pay for google glasses)

At the end, HTC, ASUS, and ACER, they are once the leading manufacturer of smartphone, PC,  and Notebook, but they are not any more now due to the lock of innovation. Their profit becomes lower and lower and even worse and worse.
As an indication of looking for job, my advise is "Working and Improving yourself as the time go by, not just reproduce and resolve the bugs".